1 / 60

Chapter 2 Simple C Programs

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 */

gail-mullen
Download Presentation

Chapter 2 Simple C Programs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 2Simple C Programs

  2. Program Structure preprocessing directives int main(void) { declarations statements }

  3. 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 {}

  4. 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;

  5. 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

  6. 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

  7. 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

  8. Are the following Valid Identifiers? • initial_time • DisTaNce • X&Y • rate% • x_sum • switch • distance • 1x • x_1

  9. C Numeric Data Types

  10. Example Data-Type Limits

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. } } 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

  22. 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;

  23. Precedence of Arithmetic Operators (updated)

  24. 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);

  25. 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

  26. 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

  27. 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

  28. Standard Input and Output

  29. 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>

  30. 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

  31. Conversion Specifiers for Output Statements Frequently Used

  32. Standard Output Output of -145 Output of 157.8926

  33. 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);

  34. 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

  35. 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

  36. Conversion Specifiers for Input Statements Frequently Used

  37. 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

  38. 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); }

  39. 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?

  40. Exercise: Read two points from user printf(“enter x1 y1: “); scanf(“%lf %lf“, &x1, &y1); printf(“enter x2 y2: “); scanf(“%lf %lf“, &x2, &y2);

  41. Library Functions

  42. 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.

  43. 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 [-, ].

  44. 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));

  45. 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);

  46. 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

  47. 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

  48. 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

  49. Exercise • Write a program to compute the volume of a cylinder of radius r and height h r h

  50. Problem Solving Methodology • 1. Problem Statement • 2. Input/Output Description • 3. Hand Example • 4. Algorithm Development • 5. Testing

More Related