ET156 Introduction to C Programming g Unit 22 C Language Elements, Input/output functions, ARITHMETIC EXPRESSIONS AND LIBRARY FUNCTIONS Instructor : Stan Kong Email : skong@itt tech.edutech.edu
General Form of a C program preprocessor directives main function heading { } declarations executable statements
Comments A "comment" is a sequence of characters beginning with a forward slash/asterisk combination (/*) that is treated as a single white space character by the compiler and is otherwise ignored. A comment can include any combination of characters from the representable character set, including newline characters, but excluding the "end comment" delimiter (*/). The compiler ignores the characters in the comment. /* This is a comment */
Preprocessor Directives #include Directive for Defining identifiers from Standard Libraries SYNTAX #include <standard header file> Examples: #include <stdio.h> #include <math.h> Define Directive for Creating Constant Macros SYNTAX #define NAME value Examples: #define PI 3.141593
Variable Declarations Thememorycells used for storing a program s input data and its computational results are called variables. The variable declarations tell the C compiler the names of all variables and what kind of information will be stored in each variable. The general format for variable declaration is: Data type variable name or variable list; Example : int count; where int is data type of integer and count is the variable name.
Data type Common data type int store integer char store single character Double store real number/floating number
Variables/User Defined Identifiers A variable may be defined using any uppercase or lowercase character, a numerical digit (0 through 9), and the underscore character (_). The first character of the variable may not be a numerical digit. C reserved word cannot be used as an variable name. Variable names are case sensitive. Valid identifiers letter_1, cent, Hello, Invalid identifier 1Letter double Two*Four Reason invalid Begin with a letter Reserve word Character * not allowed
C Reserved Words auto double include static break elif int struct case else long switch char enum main typedef const extern register union continue float return unsigned default for short void define goto signed volatile do if sizeof while
scanf Function scanf("%lf", &variable name); Read the floating point number into the address of the memorycell referenced by the variable miles.
printf Function function arguments printf("that equals %f kilometers.\n", kms); function name format string print list That equals 16.090000 kilometers
Executable Statements An assignment Statements store a value or computational result in a variable, and is used to perform most arithmetic operations in a program. Example : kms = KMS_PER_MILE MILE * miles;
Table 26 2.6 Arithmetic Operators
Unary vs. Binary Operators Unary Operators Binary Operators Take one operand Take two operands Negation ( ) operator Subtraction Plus (+) operator Addition Examples Multiplication x = -y; Division p = +x * y; Examples x = y + z; z = y z;
Rules of Precedence Parentheses rule Expressions in parentheses are evaluated separately. Nested parentheses are evaluated from the inside out. Operator precedence rule 1.unary +, 2.*, /, % 3.binary +, Associativity rule Unaryoperators at thesame level are evaluated right to left. Binary operators at the same level are evaluated left to right.
Rules of Precedence example result = 4 + 5 * 6 10/2; result = 29
Expression Assignment Assignment can cause data to be lost if target variable is of a data type more narrow than the expression double x; int n; x = 9 * 0.5; 4.5 4 n = 9 * 0.5; x n
Data Type Expression Example m = 3; n = 2; p = 2.0; x = m / p; y = m / n; Int y ;
Casting a Variable's Type
Formatting Output of Type int Table 2.11 Displaying 234 and 234 Using Different Placeholders
Formatting scientific rotation In scientific notation all numbers are written like this: Ordinary decimal Scientific Cformatting C formatting C formatting notation notation output %E output %e output %.2E (normalized) 300 3 10² 3.000000E+02 3.000000e+02 3.00E+02 4,000 4 10³ 4.000000E+03 4.000000e+03 4.00E+03 5,720,000,000 5.72 10⁹ 5.720000E+09 5.720000e+09 5.72E+09 0.0000000061 6.1 10 ⁹ 6.100000E 09 6.100000e 09 6.10E 09
Formatting Output of Type double Table 2.13
Interactive Mode vs. Batch Mode Interactive Mode Accepts input from users Sends output to the display Batch Mode Accepts input from a file metric <mydata Should echo input using printf Might output data to a file metric >myoutput
Input redirection/output redirection Redirect input from file instead of keyboard EXAMPLE : metric metric <mydata Redirect output to a file EXAMPLE : metric >myoutput
Program Controlled input and output Files Declare a file pointer variable in which to store the information necessary to permit access to a file. File pointer variable are of type FILE *. Example : FILE *inp, /* pointer to input file */ *opt; /* pointer to output file */ Prepare file to open for read, write inp = fopen("distance distance.dat dat", "r"); r); opt = fopen("distance.out", "w");
Interactive program example /* Converts distances from miles to kilometers. */ #include <stdio.h> /* printf, scanf definitions */ #define KMS_PER_MILE 1.609 /* conversion constant */ Int main(void) { double miles, /* distance in miles */ kms; /* equivalent distance in kilometers */ /* Get and echo the distance in miles. */ printf("enter Distance in miles is "); scanf( "%lf", &miles); printf("the distance in miles is %.2f.\n", miles); /* Convert the distance to kilometers. */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers. */ printf( "That equals %.2f kilometers.\n", kms); return (0); }
Sample program to use file i/o 1 /* Converts distances from miles to kilometers. */ #include<stdio <stdio.h> /* printf, scanf, fprint, fscanf, fopen, fclose definitions */ #define KMS_PER_MILE 1.609 /* conversion constant */ int main(void) { double miles, /* distance in miles */ kms; /* equivalent distance in kilometers */ FILE *inp inp, /* pointer to input file */ *outp; /* pointer to output file */ /* Open the input and output files. */ inp = fopen("distance.dat dat", "r"); r); outp = fopen("distance.out", "w"); /* Get and echo the distance in miles. */ fscanf(inp, "%lf", &miles); fprintf(outp, "The distance in miles is %.2f.\n", miles);
Sample program to use file i/o 2 /* Convert the distance to kilometers. */ kms = KMS_PER_MILE * miles; /* Display the distance in kilometers. */ fprintf(outp, "That equals %.2f kilometers.\n", kms); /* Close files. */ fclose(inp); fclose(outp); } return (0);
Figure 3.6 Function sqrt as a Black Box
Syntax Errors Code violates a grammar error of C Compiler locates syntax errors during translation Examples: Missing semicolon Undeclared variables Unclosed comments Mismatched open and close braces, quotation marks, or parentheses
Runtime Error Detected during program execution Caused by an attempt to perform an illegal operation
Logic Errors Errors in the algorithm Causes program to give incorrect results Avoid idby desk checking ki algorithm before bf coding
Top Down Design A problem solving method in which you first break a problem into its major subproblems and then solve the subproblems to derive the solution to the original problem. Structure Chart A documentation tool that shows the relationships among the subproblems of a problem.
Figure 3.10 Structure Chart for Drawing a Stick Figure
Quiz, Labs, Homework First Quiz next week covered Unit 1 & Unit2. 2 nd Lab due to day. 2 nd Assignment due next week.