800 likes | 825 Views
CSCI-125/ENGR-144 Engineering Problem Solving with C Ch 2. 2.1 Program Structure. /*-----------------------------------------*/ /* Program chapter1_1 */ /* This program computes the */ /* distance between two points. */ #include < stdio.h >
E N D
CSCI-125/ENGR-144 Engineering Problem Solving with C Ch 2
/*-----------------------------------------*/ /* Program chapter1_1 */ /* This program computes the */ /* distance between two points. */ #include <stdio.h> #include <math.h> int main(void) { /* 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); return 0; /* Exit program. */ } /*-----------------------------------------*/ Comments Preprocessor, standard C library every C program must have main function, this one takes no parameters and it returns int value { begin Variable declarations, initial values (if any) Statements must end with ; indentation indentation indentation return 0 } end of function
General Form • 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 a return0; statement preprocessing directives int main(void) { declarations statements }
Another Program /***************************************************/ /* Program chapter1 */ /* This program computes the sum of 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); system("pause"); /* keep DOS window on the screen*/ return 0; /* Exit program. */ } /****************************************************/
2.2 Constants and Variables • What is a variable in math? f(x) = x2+x+4 • In C, • A variable is a memory location that holds a value • An identifier or variable name is used to reference a memory location.
Memory double x1=1,x2=7,distance; name address Memory - content … 11 12 13 14 15 16 … How many memory cells does your computer have? Say it says 2Gbyte memory? 1K=103 or 210 = 1024 1M=106 or 220 = 10242 1G=109 or 230 = 10243 x1 x2 distance
Rules for selecting a valid identifier (variable name) • Must begin with an alphabetic character or underscore (e.g., abcABC_) • May contain only letters, digits and underscore (no special characters ^%@) • Case sensitive (AbC, aBc are different) • Cannot use C keywords as identifiers (e.g., if, case, while)
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
Memory name address Memory - content How to represent ‘a’ ? char My_letter=‘a’; int My_number = 97 Always we have 1’s and 0’s in the memory. It depends on how you look at it? For example, 01100001 is 97 if you look at it as int, or ‘a’ if you look at it as char ‘3’ is not the same as 3 0 1 2 3 4 5 6 … My_letter My_number
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
Constants • A constant is a specific value that we use in our programs. For example 3.14, 97, ‘a’, or “hello” • In your program, int a = 97; char b =‘a’; double area, r=2.0; double circumference; area = 3.14 * r*r; circumference = 2 * 3.14 * r; a b area circumference r
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
2.3 Assignment Statements • Used to assign a value to a variable • General Form: identifier = expression; /* ‘=‘ means assign expression to identifier */ • Example 1 double sum = 0; • Example 2 int x; x=5; • Example 3 char ch; ch = ‘a’; sum x ch
Assignment examples (cont’d) • Example 3 int x, y, z; x = y = 0; right to left! Z = 1+1; • Example 4 y=z; y=5; x y z 2 5
Assignment examples with different types 2 int a, b=5; double c=2.3; … a=c; /* data loss */ c=b; /* no data loss */ a b c 5.0 long double, double, float, long integer, integer, short integer, char • Data may be lost. Be careful! No data loss
Exercise: swap • Write a set of statements that swaps the contents of variables x and y x 3 x 5 y 5 y 3 Before After
Exercise: swap First Attempt x=y; y=x; x x x 3 5 5 y 5 y 5 y 5 Before After x=y After y=x
Exercise: swap Solution temp= x; x=y; y=temp; x x x x 5 3 5 3 y 3 5 5 5 y y y temp temp temp temp ? 3 3 3 Before after temp=x after x=y after y = temp Will the following solution work, too? temp= y; y=x; x=temp; Write a C program to swap the values of two variables
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 (cont’d) • 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 X 5
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
Implement a program that computes/prints simple arithmetic operations Declare a=2, b=5, c=7, d as int Declare x=5.0, y=3.0, z=7.0, w as double d = c%a Print d d = c/a Print d w = z/x Print w d = z/x Print d w = c/a Print w a=a+1 Print a … try other arithmetic operations too..
Exercise • int a=27, b=6, c; c = b%a; 2. int a=27, b=6; float c; c = a/(float)b; 3. int a; float b=6, c=18.6; a = c/b; 4. int b=6; float a, c=18.6; a = (int)c/b;
Mixed operations and Precedence of Arithmetic Operators int a=4+6/3*2; a=? int 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
Extend the previous program to compute/print mixed arithmetic operations Declare a=2, b=5, c=7, d as int Declare x=5.0, y=3.0, z=7.0, w as double d = a+c%a Print d d = b*c/a Print d w = y*z/x+b Print w d = z/x/y*a Print d w = c/(a+c)/b Print w a=a+1+b/3 Print a … try other arithmetic operations too..
} } 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; !!! x *= 4+2/3 x = x*4+2/3 wrong x=x*(4+2/3) correct
Writing a C statement for a given MATH formula • Area of trapezoid area = base*(height1 + height2)/2; • How about this
Exercise Tension = 2*m1*m2 / m1 + m2 * g; wrong Tension = 2*m1*m2 / (m1 + m2) * g • 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: Arithmetic operations a b c x y • 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 = 12 b = 3 c= 5 x = 25.0000 y = 43.0000
Exercise: Arithmetic operations • Show how C will perform the following statements and what will be the final output? int a = 6, b = -3, c = 2; c= a - b * (a + c * 2) + a / 2 * b; printf("Value of c = %d \n", c);
Step-by-step show how C will perform the operations c = 6 - -3 * (6 + 2 * 2) + 6 / 2 * -3; c = 6 - -3 * (6 + 4) + 3 * -3 c = 6 - -3 *10 + -9 c = 6 - -30 + -9 c = 36 + -9 c = 27 • output: Value of c = 27
Step-by-step show how C will perform the operations int a = 8, b = 10, c = 4; c = a % 5 / 2 + -b / (3 – c) * 4 + a / 2 * b; printf("New value of c is %d \n", c);
2.4 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
Special Characters \n newline each escape sequence \t tab represents only one \b backspace character \\ backslash \? Question mark \’ Single quote \” Double quote /*what does this print? */ • printf(“\”The End.\” \n”); • printf(“\nA\nB\tC\nDE\aF\n”);
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
2 customer_status address operator ? customer_status scanf() • int customer_status = 2; • scanf(“%d”, &customer_status); before scanf() after scanf() only conversion code(s) no plain text • Scanf() can • input all types of data • input only specific characters • Skip or exclude specific characters new value is whatever was keyed by user
Conversion Specifiers for Input Statements Frequently Used