Simple C Programs
Program Structure preprocessing directives int main(void) { declarations statements }
Program Structure Comments begin with the characters /* and end with the characters */ /* compute distance between two points */ Preprocessor directives give instructions to the compiler #include <math.h> Every C program contains one function named main int main() { statements } The body of the main function is enclosed by braces {}
Program Structure The main function contains two types of commands: declarations and statements Declarations and statements are required to end with a semicolon (;) Preprocessor directives do not end with a semicolon To exit the program, use return 0;
Preprocessor Directive First Program Comments /******************************************************************/ /* Program chapter1 */ /* */ /* This program computes the sum two numbers */ #include <stdio.h> int main(void) { /* Declare and initialize variables. */ double number1 = 473.91, number2 = 45.7, sum; /* Calculate sum. */ sum = number1 + number2; /* Print the sum. */ printf(“The sum is %5.2f \n”, sum); /* Exit program. */ return 0; } /*************************************************************/ Preprocessor Directive No semicolon! Main function Variable Declarations Statements Exit the program
Constants and Variables A variable is a memory location that is assigned a name or an identifier An identifier is used to reference a memory location. Memory snapshot
Rules for Selecting a valid identifier (variable name) Must begin with an alphabetic character or underscore May contain only letters, digits and underscore (no special characters) Case sensitive Can not use keywords as identifiers
Are the following Valid Identifiers? initial_time DisTaNce X&Y distance 1x x_1 rate% x_sum switch
C Numeric Data Types
Example Data-Type Limits
C Character Data Type: char char result =‘Y’; In memory, everything is stored as binary value, which can be interpreted as char or integer. Examples of ASCII Codes
Symbolic Constants What if you want to use a better estimate of ? For example, you want 3.141593 instead of 3.14. You need to replace all by hand Better solution, define as a symbolic constant, e.g. #define PI 3.141593 … area = PI * r * r; circumference = 2 * PI * r; Defined with a preprocessor directive Compiler replaces each occurrence of the directive identifier with the constant value in all statements that follow the directive
a variable of type float Example No selicolon! #define PI 3.141593 int main() { int x,y,z; int a; int b; float f1; double d1; return 0; } 3 variables of type int a variable of type float
Assignment Statements Used to assign a value to a variable General Form: identifier = expression; Example 1 double sum = 0; sum Example 2 int x; x=5; x Example 3 char ch; ch = ‘a’; ch 5 a
Assignment Statements Example 3 int x, y, z; x=y=0; z=2; x y z Example 4 y=z; y 2 2
Arithmetic Operators Addition + sum = num1 + num2; Subtraction - age = 2007 – my_birth_year; Multiplication * area = side1 * side2; Division / avg = total / number; Modulus % lastdigit = num % 10; Modulus returns remainder of division between two integers Example 5%2 returns a value of 1 Binary vs. Unary operators All the above operators are binary (why) - is an unary operator, e.g., a = -3 * -4
Arithmetic Operators Note that id = exp means assign the result of exp to id, so x=x+1 means first perform x+1 and Assign the result to x Suppose x is 4, and We execute x=x+1 4 5 X
Integer division vs Real division Division between two integers results in an integer. The result is truncated, not rounded Example: int A=5/3; A will have the value of 1 int B=3/6; B will have the value of 0 To have floating point values: double A=5.0/3; A will have the value of 1.666 double B=3.0/6.0; B will have the value of 0.5
Precedence of Arithmetic Operators Mixed operations: a=4+6/3*2; a=? b=(4+6)/3*2; b=? a= 4+2*2 = 4+4 = 8 b= 10/3*2 = 3*2= 6 5 assign = Right to left
Priority of Operators Compute the following Area of trapezoid 2*(3+2) 2*3+2 6-3*2 Area of trapezoid area = 0.5*height*(base_1+base_2); base_1 height base_2
Increment and Decrement Operators Increment Operator ++ post increment x++; pre increment ++x; Decrement Operator -- post decrement x--; pre decrement --x; } x=x+1; } x=x-1; But, the difference is in the following example. Suppose x=10; A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11 B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11
Abbreviated Assignment Operator operator example equivalent statement += x+=2; x=x+2; -= x-=2; x=x-2; *= x*=y; x=x*y; /= x/=y; x=x/y; %= x%=y; x=x%y;
Precedence of Arithmetic Operators (updated)
Exercise Write a C statement to compute the following f = (x*x*x-2*x*x+x-6.3)/(x*x+0.05*x+3.14);
Exercise Write a set of statements that swaps the contents of variables x and y 3 5 5 3 x y x y Before After
Exercise First Attempt x=y; y=x; 3 5 5 5 5 5 x y x y x y Before After x=y After y=x
Exercise Solution temp= x; x=y; y=temp; 3 5 ? 3 5 3 5 5 3 5 3 3 x y Before after temp=x after x=y after y = temp
Standard Input and Output
Standard Input and Output Output: printf Input: scanf Remember the program computing the distance between two points! /* Declare and initialize variables. */ double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; How can we compute distance for different points? It would be better to get new points from user, right? For this we will use scanf To use these functions, we need to use #include <stdio.h>
Standard Output printf Function prints information to the screen requires two arguments control string Contains text, conversion specifiers or both Identifier to be printed Example double angle = 45.5; printf(“Angle = %.2f degrees \n”, angle); Output: Angle = 45.50 degrees Conversion Specifier Control String Identifier
Conversion Specifiers for Output Statements Frequently Used
Standard Output Output of -145 Output of 157.8926 Specifier Value Printed %i -145 %4d %3i %6i __-145 %-6i -145__ %8i ____-145 %-8i -145____ Specifier Value Printed %f 157.892600 %6.2f 157.89 %7.3f 157.893 %7.4f 157.8926 %7.5f 157.89260 %e 1.578926e+02 %.3E 1.579E+02
Exercise int sum = 65; double average = 12.368; char ch = ‘b’; Show the output line (or lines) generated by the following statements. printf("Sum = %5i; Average = %7.1f \n", sum, average); printf("Sum = %4i \n Average = %8.4f \n", sum, average); printf("Sum and Average \n\n %d %.1f \n", sum, average); printf("Character is %c; Sum is %c \n", ch, sum); printf("Character is %i; Sum is %i \n", ch, sum);
Exercise (cont’d) Solution Sum = 65; Average = 12.4 Sum = 65 Sum and Average 65 12.4 Character is b; Sum is A Character is 98; Sum is 65
Standard Input scanf Function inputs values from the keyboard required arguments control string memory locations that correspond to the specifiers in the control string Example: double distance; char unit_length; scanf("%lf %c", &distance, &unit_length); It is very important to use a specifier that is appropriate for the data type of the variable
Conversion Specifiers for Input Statements Frequently Used
Exercise float f1; int i1; scanf(“%f %d”,&f1,&i1); f1 is float and conversion specifier for float is f i1 is integer and conversion specifier for integer is %f float f1; int i1; scanf(“%f %d”,&f1,&i1); What will be the values stored in f and i after scanf statement if following values are entered 12.5 1 12 45 12 23.2 12.1 10 12 1
Program #include <stdio.h> int main() { float f1; int i1; scanf("%f %i",&f1,&i1); printf("f=%f i=%i\n",f1,i1); system(“pause”); return(0); }
Good practice You don’t need to have a printf before scanf, but it is good to let user know what to enter: Printf(“Enter x y : ”); Scanf(“%d %d”, &x, &y); User may not know what to do of you have a scanf statement only What will happen if you forget the & before the variable name?
Exercise: Read two points from user printf(“enter x1 y1: “); scanf(“%lf %lf“, &x1, &y1); printf(“enter x2 y2: “); scanf(“%lf %lf“, &x2, &y2);
Library Functions
Math Functions fabs(x) Absolute value of x. sqrt(x) Square root of x, where x>=0. pow(x,y) Exponentiation, xy. Errors occur if x=0 and y<=0, or if x<0 and y is not an integer. ceil(x) Rounds x to the nearest integer toward (infinity). Example, ceil(2.01) is equal to 3. floor(x) Rounds x to the nearest integer toward - (negative infinity). Example, floor(2.01) is equal to 2. exp(x) Computes the value of ex. log(x) Returns ln x, the natural logarithm of x to the base e. Errors occur if x<=0. log10(x) Returns log10x, logarithm of x to the base 10. Errors occur if x<=0.
Trigonometric Functions sin(x) Computes the sine of x, where x is in radians. cos(x) Computes the cosine of x, where x is in radians tan(x) Computes the tangent of x, where x is in radians. asin(x) Computes the arcsine or inverse sine of x, where x must be in the range [-1, 1]. Returns an angle in radians in the range [-/2,/2]. acos(x) Computes the arccosine or inverse cosine of x, Returns an angle in radians in the range [0, ]. atan(x) Computes the arctangent or inverse tangent of x. The Returns an angle in radians in the range [-/2,/2]. atan2(y,x) Computes the arctangent or inverse tangent of the value y/x. Returns an angle in radians in the range [-, ].
Exercise velocity = sqrt(vo*vo+2*a*(x-xo)); Write an expression to compute velocity using the following equation Assume that the variables are declared velocity = sqrt(vo*vo+2*a*(x-xo));
Exercise center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/ Write an expression to compute velocity using the following equation Assume that the variables are declared center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/ ((pow(r,2)-pow(s,2))*a);
Memory Requirement of Types Integer Types short: 2 bytes int: 4 bytes long: 4 bytes Floating point Types 35.216 = 0.35216*102 float: 4 bytes double: 8 bytes long double: 12 bytes See chapter2e2.c 16 0101011111111111 1 23 8
Exercise: Arithmetic operations ? 5 Show the memory snapshot after the following operations by hand int a, b, c=5; double x, y; a = c * 2.5; b = a % c * 2 - 1; x = (5 + c) * 2.5; y = x – (-3 * a) / 2; Write a C program and print out the values of a, b, c, x, y and compare them with the ones that you determined by hand. a b c x y
Solution #include <stdio.h> int main() { int a, b, c=5; double x, y; a = c * 2.5; b = a % c * 2 - 1; x = (5 + c) * 2.5; y = x - (-3 * a) /2; printf("a = %d b = %d c= %d x = %5.4f y = %5.4f \n", a, b, c, x, y); system("pause"); return 0; } a = 12 b = 3 c= 5 x = 25.0000 y = 43.0000
Character Functions toupper(ch) If ch is a lowercase letter, this function returns the corresponding uppercase letter; otherwise, it returns ch isdigit(ch) Returns a nonzero value if ch is a decimal digit; otherwise, it returns a zero. islower(ch) Returns a nonzero value if ch is a lowercase letter; otherwise, it returns a zero. isupper(ch) Returns a nonzero value if ch is an uppercase letter; otherwise, it returns a zero. isalpha(ch) Returns a nonzero value if ch is an uppercase letter or a lowercase letter; otherwise, it returns a zero. isalnum(ch) Returns a nonzero value if ch is an alphabetic character or a numeric digit; otherwise, it returns a zero.
Exercise Given a 3 digit number in the range [100.999] Write a program to reverse it For example, num is 258, reverse is 852 num is 123, reverse is 321 num is 111, reverse is 111 How to do it First approach: Swap first and last digit Second approach: Split number into digits and combine them in reverse order
Exercise continued Suppose you have number 258 How can you compute the last digit? Find remainder when you divide 258 by 10 d3 = 258 % 10 -> 8 How can you compute the first digit? Divide 258 by 100 and keep integer part d1 = 258 / 100 -> 2 How can you compute the middle digit? Get the last 2 digits by finding remainder after division by 100 Divide last 2 digits by 10 and keep the integer part d2 = 258 % 100 / 10 -> 58/10 -> 5 Construct a reverse number with the digits number2 = d3*100+d2*10+d1 -> 8*100+5*10+2 -> 852