Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Programming Techniques Semester 1, 1998

Similar presentations


Presentation on theme: "Computer Programming Techniques Semester 1, 1998"— Presentation transcript:

1 240-222 Computer Programming Techniques Semester 1, 1998
2. Control Flow Section 3.10 Objectives of these slides: to introduce the main kinds of C control flow

2 Overview 1. Three/Four Kinds of Control Flow 2. The if Statement
3. The while Statement 4. Grades Average Example 5. Incrementing and Decrementing continued

3 6. Counter-controlled Repetition
7. The for Statement 8. The switch Statement 9. The break Statement 10. More Complex Input

4 1. Three/Four Kinds of Control Flow
sequence choice (branches) e.g. if and switch statements loops (iteration) e.g. while and for statements recursion

5 2. The if statement : scanf("%d", &grade); if (grade >= 60) printf("Passed\n"); else { printf("Failed\n"); printf("Repeat Course\n"); } scanf("%d", &grade); :

6 : if (temp < 0) setting = setting + 20; else if (temp < 10) setting = setting + 10; else setting = setting + 1; :

7 2. The while statement (sum.c)
/* sum between 1 and 10 */ #include <stdio.h> int main() { int i = 1, sum = 0; while (i <= 10) { sum = sum + i; i = i + 1; } printf("Sum is %d\n", sum); return 0; }

8 Compile and run $ gcc -Wall -o sum sum.c $ sum Sum is 55

9 The while statement has the form:
while ( condition ) statement The while keeps executing its (compound) statement until its condition becomes false Deciding on a loop condition can be very difficult

10 Flow Chart for while condition true statement false
code after while-loop

11 Square Root Example /* find square root of n using Newton Raphson method */ #include <stdio.h> int main() { float n, x0, eps = ; printf("Enter number\n"); scanf("%f", &n); x0 = n; while ( abs(x0*x0 - n)/n > eps) x0 = (x0 + n/x0)/2; printf("Square Root is %f\n", x0); return 0; }

12 4. Grades Average Example
4.1. The Problem Statement 4.2. How to Start Writing a Program 4.3. Dissect the Problem Statement 4.4. Flesh out the Skeleton 4.5. Consider the Loop 4.6. What is an Average? 4.7. The Final Code: average.c

13 4.1. The Problem Statement Sec. 3.9
Develop a class averaging program that will process an arbitrary number of grades each time the program is run.

14 4.2. How to Start Writing a Program
Program = Algorithm + Data Structures Algorithm: a series of functions, each using a mix of sequencing, branches, loops, recursion and other functions Data Structures: they reflect the structure of the data in the Problem Statement e.g int, float, arrays, etc

15 Consider the input/output requirements
Dissect (‘Pull apart’) the Problem Statement Use top-down design (also called stepwise refinement)

16 4.3. Dissect the Problem Statement
The inputs are the grades The output is the average Use a loop to read in ‘an arbitrary number of grades’

17 4.4. Flesh Out the Skeleton /* grades.c */ #include <stdio.h> int main() { /* declare the variables */ float average; /* calculate class average using a loop to read in the grades */ printf("Class average is %f\n", average); return 0; }

18 4.5. Consider the Loop The big problem:
while ( condition?? ) { printf("Enter grade:"); scanf("%d", &grade); /* calculate the on-going average using grade */ } The big problem: what is the loop condition?

19 The Loop with a Condition
printf("Enter grade, -1 to end: "); scanf("%d", &grade); while (grade != -1) { /* calculate the on-going average using grade */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); }

20 The Skeleton with the Loop
/* grades.c */ #include <stdio.h> int main() { /* declare the variables */ float average; int grade; printf("Enter grade, -1 to end: "); scanf("%d", &grade); : continued

21 while (grade. = -1) { /. calculate the on-going average using grade
while (grade != -1) { /* calculate the on-going average using grade */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); } printf("Class average is %f\n",average); return 0; }

22 4.6. What is an Average? average = total of grades / number of grades
Use two new variables: total counter

23 4.7. The Final Code: average.c Sec. 3.9
/* Class Average Program */ #include <stdio.h> int main() { float average; int counter, grade, total; /* initialization phase */ total = 0; counter = 0; : continued

24 /* looping phase */ printf("Enter grade, -1 to end: "); scanf("%d", &grade); while(grade != -1) { total = total + grade; counter = counter + 1; printf("Enter grade, -1 to end: "); scanf("%d", &grade); } : : continued

25 /. termination phase. / average = (float) total / counter; /
/* termination phase */ average = (float) total / counter; /* can you see a bug ? */ printf("Class average is %.2f", average); return 0; }

26 Compile and run $ gcc -Wall -o average average.c
$ average Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 6 Enter grade, -1 to end: -1 Class average is 58.33

27 5. Incrementing and Decrementing
Add 1 to c by writing: c = c + 1; Also: c += 1; Also: c++; Also: ++c;

28 Fig. 3.13 /* Preincrementing and postincrementing */ #include <stdio.h> int main() { int c; c = 5; printf("%d\n", c); printf("%d\n",c++); /*post-increment*/ printf("%d\n\n", c); : continued

29 c = 5; printf("%d\n", c); printf("%d\n",++c); /. pre-increment
c = 5; printf("%d\n", c); printf("%d\n",++c); /*pre-increment*/ printf("%d\n", c); return 0; }

30 Output:

31 5.2. Decrementing Take 1 from c by writing: Also: c -= 1; Also: c--;
c = c - 1; Also: c -= 1; Also: c--; Also: --c;

32 6. Counter-controlled Repetition Fig. 4.1.
/* Counter-controlled repetition */ #include <stdio.h> int main() { int counter = 1; while (counter <= 10) { printf ("%d\n", counter); counter; } return 0; }

33 Output 1 2 3 : 10

34 /. Counter-controlled repetition. / #include <stdio
/* Counter-controlled repetition */ #include <stdio.h> int main() { int counter = 0; while (++counter <= 10) printf ("%d\n", counter); return 0; }

35 7. The for Statement 7.1. The Parts of a for
7.2. The for is a sort of while 7.3. Some Examples 7.4. Summation 7.5. Compound Interest

36 7.1. The Parts of a for Sec. 4.4 #include <stdio.h> int main() { int cnt; for (cnt = 1; cnt <= 10; cnt++) printf("%d\n", cnt); return 0; } the increment occurs after the loop body has been executed test for continuing initial value final value increment

37 Flow Chart for for-loop
initial value test for continuing true body (e.g. printf) increment false code after for-loop

38 7.2. The for is a sort of while
for (expr1; expr2; expr3) statement; is equivalent to: expr1; while (expr2) { statement; expr3; }

39 7.3. Some Examples for(i = 7; i <=77; i += 7) statement;

40 x =2; y = 10; for(j = x; j <= 4*x*y; j += y/x) statement;
equivalent to: for(j = 2; j <= 80; j += 5) statement;

41 for(j = 10; j > 20; j++) statement;
equivalent to: j = 10;

42 7.4. Summation fig. 4.5 /* Summation using a for-loop */ #include <stdio.h> int main() { int sum = 0, num; for (num = 2; num <= 100; num += 2) sum += num; printf("Sum is %d", sum); return 0; }

43 7.5. Compound Interest Fig. 4.6 Amount = principal * (1 + rate)year

44 /. Calculating compound interest for 10 years. / #include <stdio
/* Calculating compound interest for 10 years */ #include <stdio.h> #include <math.h> int main() { int year; double amount, principal = , rate = 0.05; printf("%4s%21s\n", "Year", "Amount on deposit"); : continued

45 for (year = 1; year <= 10; year++) { amount = principal
for (year = 1; year <= 10; year++) { amount = principal * pow(1 + rate, year); printf("%4d%10.2f\n", year, amount); } return 0; }

46 Some Points On p.864 of D&D: Also look at math.h in /usr/include
pow()'s arguments should be doubles,: if they are integer or float then they are cast into doubles (e.g. year). On p.864 of D&D: double pow(double x, double y); Also look at math.h in /usr/include

47 Compile and run % gcc -Wall -o compound compound.c
% compound Year Amount on deposit : :

48 Explicit Libraries But on some machines: Must type:
% gcc -Wall -o compound compound.c ld: undefined: pow Must type: % gcc -Wall -o compound compound.c -lm

49 8. The switch Statement 8.1. The Parts of a switch
8.2. Counting Letter Grades

50 8.1. The Parts of a switch For multiple choices: condition c1 c2 c3
task-A task-B task-C

51 switch (condtion) { case c1 : task-A; break; case c2 : task-B; break; case c3 : task-C; break; : }

52 8.2. Counting Letter Grades Fig. 4.7
/* Counting letter grades */ #include <stdio.h> int main() { int grade; int acount = 0, bcount = 0, ccount = 0, dcount = 0, fcount = 0; printf("Enter the letter grades.\n"); printf("Enter EOF to end.\n"); : continued

53 while ((grade = getchar())
while ((grade = getchar()) != EOF) { switch (grade) { case 'A': case 'a': acount; break; case 'B': case 'b': bcount; break; case 'C': case 'c': ccount; break; case 'D': case 'd': dcount; break; : : continued

54 case 'F': case 'f': fcount; break; case '\n': case' ': break; default: printf("Incorrect letter grade entered."); printf(" Enter a new grade.\n"); break; } } : : important continued

55 printf("\nThe totals for each
printf("\nThe totals for each letter grade are:\n"); printf("A: %d\n", acount); printf("B: %d\n", bcount); printf("C: %d\n", ccount); printf("D: %d\n", dcount); printf("F: %d\n", fcount); return 0; }

56 Some Points Very common coding style:
while((grade = getchar()) != EOF) { : } getchar() reads the next character as an integer and assigns it to grade EOF is an integer constant representing the end-of-file value. Defined in stdio.h

57 The line includes the newline character (represented by '\n')
getchar() will only start reading a line of characters when it has been terminated with a return or EOF. The line includes the newline character (represented by '\n')

58 Output from letter grades program
Enter the letter grades. Enter EOF to end input. A B C C A X Incorrect letter grade entered. Enter a new grade. D : I typed return and <ctrl>D continued

59 Totals for each letter grade were: A: 2 B: 1 C: 2 D: 1

60 9. The break Statement Sec. 4.9
Causes execution to jump to the next statement after the loop (or switch) containing the break. while(1) { scanf("%lf", &x); if (x < 0.0) break; printf("%f\n", sqrt(x)); } /* break jumps to here */ :

61 10. More Complex Input If you want to read several values from a line, then use scanf(), and check its return value. scanf() returns the number of values it has read in. Example: assume each line contains two integers and a float:

62 Code Fragment int d1, d2; float f; : while (scanf(“%d %d %f”, &d1, &d2, &f) == 3) /* do something with input values */ :

63 Note The spaces between the numbers (including tabs and newlines) are ignored by scanf() when it is looking for things to read in. e.g. could write:


Download ppt "Computer Programming Techniques Semester 1, 1998"

Similar presentations


Ads by Google