ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include <stdio.h> #include <stdlib.h> #include <math.h> main() { /* Declare and initialize variables */ double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; /* Compute sides of a right triangle */ side_1=x2-x1; side_2=y2-y1; distance=sqrt(side_1*side_1 + side_2*side_2); /* Print distance */ printf ( the distance between the two points is %5.2f \n, distance); /* Exit program */ return EXIT_SUCCESS; } /* */ Comments Preprocessor directives: #include <stdio.h> information related to the output statement #include <stdlib.h> contains a constant we will use in exiting the program #include <math.h> contains information related to the function used to compute the square root of a value h extension specifies header files 1
< and > around the file names indicate that the files are included with the Standard C Library. This library is contained in the files that accompany ANSI C compiler. main contains two types of commands, declarations and statements. The declarations define the memory locations that will be used by the statements. The declarations may or may not give initial values to be stored in the memory locations. The following is the declarations part along with the comment preceding. /* Declare and initialize variables */ double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; double indicates that the variable is double-precision floating-point The statements specify the operations to be performed in this program. /* Compute sides of a right triangle */ side_1=x2-x1; side_2=y2-y1; distance=sqrt(side_1*side_1 + side_2*side_2); /* Print distance */ printf ( the distance between the two points is %5.2f \n, distance); ATTENTION : DECLARATIONS AND STATEMENTS MUST END WITH A SEMICOLON!!! (Note: The details of the syntax in the statements will be discussed in a little bit!) To exit the program we use a return statement. The general form of a C program is: preprocessing functions main() { declarations; statements; } 2
Constants and Variables Constants are specific values, 2, 3.14, -15 Variables are memory locations that are assigned a name or identifier Identifiers are used to reference the value stored in the memory location Rules for selecting Identifiers 1. An identifier must begin with an alphabetic character or the underscore character 2. Alphabetic characters in an identifier can be lowercase or uppercase 3. An identifier can contain digits, but not as the first character 4. An identifier can be of any length but the first 31 characters`of the identifier must be unique 5. An identifier cannot be any of the keywords ( = words with special meaning to the C compiler) Attention: C is case sensitive KEYWORDS auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continuous for signed void default goto sizeof volatile do if static while Scientific Notation A floating-point value represents both integer and non-integer values ( 2.5, -0.004) In scientific notation it is written as a mantissa times a power of 10. The mantissa has an absolute value greater than or equal to 1.0 and less than 10.0 ( e.g. 2.56 = 2.56 x 10 1 ) In exponential notation the letter e is used to separate the mantissa from the exponent of the power of ten. ( e.g. 2.56 = 2.56e1, 1.5 = 1.5e0) The number of digits for the decimal portion of the mantissa determines the precision (accuracy) and the number of digits allowed for the exponent determines the range. Numeric Data Types Thet are either integers or floating-point values. Non-numeric data types will be discussed later. 3
Numeric Data Type Limits Integers short maximum = 32,767 int maximum = 32,767 long maximum = 2,147,483,647 Floating Point float 6 digits of precision maximum exponent = 38 double Symbolic Constants PI 3.141593 maximum value = 3.402823 e + 38 15 digits of precision maximum exponent = 308 maximum value = 1.797693 e + 308 long double 19 digits of precision maximum exponent = 4932 maximum value = 1.189731 e + 4932 Consider the following preprocessing directive to assign the value of 3.141593 to the variable PI. #define PI 3.141593 So, area = PI*radius*radius; Assignment Statements An assignment statement is used to assign value to an identifier. The general form of the assignment statement is identifier = expression; an expression can be a constant, another variable or the result of an operation. The following two sets of statements declare and give values to the variables sum and x1. double sum = 10.5; double sum; int x1=3; int x1;. sum = 10.5; x1 = 3; The set of statements on the left define and initialize the variables at the same time the statements on the right could be used at any point in the program and thus may be used to change (as opposed to initialize) the values in variables. Multiple statements are also allowed in C as it is shown: x=y=z=0; 4
We can also assign a value from one variable to another with an assignment statement: rate = state_tax; In this case the value for the rate depends on the value of state_tax Numeric conversion : If a value is moved to a data type that is higher in order, no information will be lost; if it is moved to a value that is lower in order, information may be lost. The order is as follows: high: long double double float long integer integer low: short integer Arithmetic operators: area_square = side * side * is used for multiplication + is used for addition - is used for subtraction / is used for division Consider this x = x + 1; In algebra this statement is not valid. In C it meas that x is assigned the value of x plus 1. For example if the value of x is 5 before the execution of the statement, after the execution the value of x will be 6. C also uses a modulus operator, %, which is used to compute the remainder in a division between two integers. Examples 5%2 = 1, 7%2=1 6%3=0 a=9, b=4 then a/b = 2 and a%b = 1. Of course you are not allowed to divide by zero! Binary operators ( *, +, -, /, %): they operate on two values. The result of the binary oprators with values of the same type is also a value of the same type. Unary operators (+, -): they operate on one value, e.g. -x Keep in mind: an integer division can sometimes produce unexpected results because any decimal portion of the integer is dropped; the result is a truncated result not a rounded result. Mixed operation: an operation between values of different types. Before the noperation is performed, the value with the lower type is converted or promoted to the higher type and the operation is performed with values of the same type. 5
Int sum, count; float average; average = sum/count; If sum = 18 and count = 5 the average = 3 not 3.6!!!!!! To compute the sum correctly we use a cast operator a unary operator that allows us to specify a type change in the value before the next computation. So, average = (float) sum/count; Priority of operations Overflow and Underflow Increment and decrement operators ++count; count++; y--; is equivalent to y=y-1; w = ++x-y is equivalent to x=x+1; w=x-y; Precedence of Arithmetic Operators Precedence Operator Associativity 1 parentheses ( ) innermost first 2 unary operators right to left + - type 3 binary operators left to right * / % 4 binary operators left to right + - w = x++ -y; is equivalent to w=x-y; x=x+1; Abbreviated assignment operators Any statrement of the form identifier = identifier operator expression; can be written in this form: identifier operator = expression; What do we mean by the following? a=b+=c+d; To evaluate this property we use the following table 6
Precedence of Arithmetic and Assignment Operators Precedence Operator Associativity 1 parentheses innermost first 2 unary operators right to left + - ++ -- 3 binary operators left to right * / % 4 binary operators left to right + - 5 assignment operators right to left =, +=, - =, /=, %= And the statement a=b+=c+d; is equivalent to the following: a=(b+= (c+d)); And if we replace the abbreviated forms with the longer forms of the operations we have a=(b=b+(c+d)); or b=b+(c+d); a=b; NOTE: USING ABBREVIATED ASSIGNMENT STATEMENTS IN A MULTIPLE ASSIGNMENT STATEMENT IS NOT RECOMMENDED!!!!! Standard Input and Output #include <stdio.h> This directive gives the compiler the information that it needs to check references to the input/output functions in the Standard C library printf FUNCTION The printf function allows us to print values and explanatory text to the screen. printf( Angle = %f radians \n, angle); The printf function contains two arguments - a control string and an identifier to specify the value to be printed. A control string is enclosed in double quotation marks and it can contain text or conversion specifiers or both. A conversion specifier describes the format to use in printing the value of a variable Let us analyze in full detail the above example. The control string specifies that the character angle will be printed on the screen. The next group of characters (%f) represents a conversion specifier that indicates that a value is to be printed next, which then will be followed by the characters radians. The next combination of characters (\n) represents new line indicator. The second argument in the printf statement is the variable angle, it is matched to the conversion specifier in the control string. Note: If the value of the angle is 2.84 the output generated by this particular example is: Angle = 2.840000 radians. 7
Now let us look closer to the conversion specifiers Numeric Conversion Specifiers for Output Statements Variable Type Output Type Specifier Integer Values short, int int %i, %d int short %hi, %hd long long %li, %ld int unsigned in %u int unsigned short %hu long unsigned long %lu Floating-Point Values float, double double %f, %e, %E, %g, %G long double Long double %Lf, %Le, %LE, %Lg, %LG For example, to print a short or an int use an %i (integer) or %d (decimal) specifier (either specifier gives the same results); and to print a long, use an %li or %ld specifier. To print a float or a double, use an %f ( floating-point form), %e (exponential form as in 2.3e+02), or %E (exponential form as in 2.3E+02). The %g (general) specifier prints the value using an %f or %e specifier, depending on the size of the value; the %G specifier is the same as the %g, except that it prints the value using an %f or %E specifier. Field width After selecting the correct specifier additional information can be added. A minimum field width can be specified along with an optional precision that controls the number of characters printed. The field width and the precision can be used together or sepaerately. If the precision is omitted, a default of 6 is used for the %f specifier. The decimal portion of a value is rounded to the specified precision; thus, the value 14.51678 will be printed as 14.52, if a %2f specification is used. The specification %5i indicates that a short or an int is to be printed with a minimum field width of 5. The field width will be increased if necessary to print the corresponding value. If the field width specifies more positions than are needed for the value the value is right-justified, which means that the extra positions are filled with blanks on the left of the value. To left-justified a value a minus sign is inserted before the field width, as in %-8i. If a plus sign is inserted before the field width as in %+6f, a sign will always be printed with a value. Example: double 157.8926 Specifier Value Printed %f 157. 892600 %6.2f 157.89 %+8.2f b+157.89 %7.5f 157. 89260 %e 1.5789260e+02 %E 1.579E+02 %G 157.893 8
Escape character The backlash, \, is an escape character when it is used in the control string. The other escape sequences recognized by C are listed below: Sequence \ a \ b \ f \ n newline \ r \ t \ v \\ \? Character Represented alert (bell) character backspace formfeed carriage return horizontal tab vertical tab backlash question mark \ single quote \ double quote scanf FUNCTION This function allows us to enter values from the keyboard when a program is executed. Suppose that a program computes the number of acres of new forest growth after a specified period of time elapses. If the time elapsed is a constant in the program, we have to change the value of the constant and then to recompile and reexecute the program to obtain the output for a different time period. Alternatively if we use the scanf function to read the time period, we do not need to recompile the program, we only need to reexecute it and enter the desired time period from the keyboard. The first argument in the scanf function is a control string that specifies the types of the variables whose values are to entered from the keyboard. The type of specifiers are shown in the following table. Numeric Conversion Specifiers for Input Statements Variable Type Specifier Integer Values int %i, %d short %hi, %hd long int %li, %ld unsigned in %u unsigned short %hu unsigned long %lu Floating-Point Values float, double %f, %e, %E, %g, %G %lf, %le, %le, %llg, %lg long double %Lf, %Le, %LE, %Lg, %LG 9
Thus for example, the specifiers for an integer variable are %i or %d; The specifiers for a float variable are %f, %e, %g; and the specifiers for a double variable are %lf, %le, %lg. It is very important to use a correct specifier. For examples errors will occur if you use an %f specifier to read the value for a double variable. The remaining arguments in the scanf function are memory locations that corrwspond to the specifiers in the control string. These memory locations are indicated with the adreess operator, &. This operator is unary operator that determines the memory address of the identifier with which it is associated. Thus, if the value to be entered through the keyboard is an integer that is to be stored in the variable year, we could use this statement to read the value: scanf( %i, &year); The precedence level of the address operator is the same as the other unary operators. If there are several unary operators in the same statement, there are associated from right to left. A common error in the scanf statement is to omit the address operator for the identifiers. If we wish to read more than one value from the keyboard we can use statements such as the following: scanf( %lf %lf, &distance, &velocity); When this statement is executed the program will read two values from the keyboard and convert them into two double values. Mathematical functions #include <math.h> fabs(x), sqrt(x), pow(x,y), ceil(x), floor(x), exp(x), log(x), log10(x), sin(x), cos(x), tan(x) Debugging Notes 1. Declarations and C statements must end with a semicolon. 2. Preprocessor directives do not enter with a semicolon. 3. If possible avoid assignments that could potentially cause information to be lost. 4. Use paretheses in a long expession to be sure it is evaluated as desired. 5. Use double precision or extrended precision to avoid problems with exponent overflow or underflow. 6. Be sure that the specifiers matches the variable type in a scanf statement. 7. Errors can occur if user input values cannot be converted correctly to the specifier variable type in a scanf statement. 8. Do not forget the address operator with identifiers in the scanf statement. 9. Remember that symbolic constant definitions do not end withn a semicolon. 10. In nested function references, each set of arguments must be in its own set of parentheses. 11. Remember that the logarithmic functions cannot be used with negative or zero values for arguments. 12. Be sure to use angles in radians with the trigonometric functions. 10
13. Remember that many of the inverse trigonometric functions and hyperbolic functions have restrictions on the ranges of allowable input values Preprocessor directives #include <stdio.h> #include <stdlib.h> #include <math.h> C Statements Summary Preprocessor directive to define a symbolic constant #define PI 3.141593 Declarations for integers short sum=0; int year_1, year_2; long k; Declarations for floating-point values float height_1, height_2; double length=10, side1, side2; long double distance, velocity; Argument statement area = 0.5 * base * (height_1+height_2); Keyboard input statement scanf( %i, &year); Screen output statement printf( The area is %f square feet \n, area); Program exit statement Return EXIT_SUCCESS; Happy Programming! 11