610 likes | 729 Views
Chapter 2 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 */
E N D
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;
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 • rate% • x_sum • switch • distance • 1x • x_1
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
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 0 5 a
Assignment Statements • Example 3 int x, y, z; x=y=0; z=2; x y z • Example 4 y=z; y 0 0 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 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 • 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
} } x=x+1; x=x-1; Increment and Decrement Operators • Increment Operator ++ • post increment x++; • pre increment ++x; • Decrement Operator -- • post decrement x--; • pre decrement --x; 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;
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 y y x x Before After
Exercise First Attempt x=y; y=x; 3 5 5 5 5 5 y y y x x x 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 y temp x y temp y temp y temp x x x Before after temp=x after x=y after y = temp
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
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 Average = 12.3680 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 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 Scanf(“%d %d”, &x, &y); • 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);
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.
TrigonometricFunctions • 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, • where x must be in the range [-1, 1]. • 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 • 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 • 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 16 • 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 0101011111111111 1 23 8
Exercise: Arithmetic operations • 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
Exercise • Write a program to compute the volume of a cylinder of radius r and height h r h
Problem Solving Methodology • 1. Problem Statement • 2. Input/Output Description • 3. Hand Example • 4. Algorithm Development • 5. Testing