Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Language  C Control Flow

Similar presentations


Presentation on theme: "Programming Language  C Control Flow"— Presentation transcript:

1 Programming Language  C Control Flow
主講人:虞台文

2 Content Overview If-Else Statement Else-If Statement Switch Statement
Loops - While and For Do-While Statement Break and Continue Goto and Labels

3 Programming Language  C Control Flow
Overview

4 Control Flow Control flow statements specify the order in which computations are performed. Sequencing Conditional Selection Looping (or iterative processing)

5 Statements and Blocks Simple Statements Null Statement
lower = 0; upper = 300; step = 20; fahr = lower; Null Statement ; // a null statement Compound Statements (block statements) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f %6.1f\n", fahr, celsius); fahr = fahr + step; } 4 simple statements 1 compound statement

6 More on Block Statements
compound-statement : { declaration-listopt statement-listopt }

7 Programming Language  C Types, Operators and Expressions
If-Else Statement

8 If-Else Statement if (expression) statement1 else statement2

9 If-Else Statement if (expression) statement1 else statement2
If expression is evaluated to nonzero, statement1 is executed; otherwise, statement2 is executed. if (expression) statement1 else statement2 expression option

10 Shortcut if(expression != 0) ... if(expression) ...

11 Dangling Else Problem z = ? z = 20 z = 3 n=5; a=2; b=3; z=20;
if (n > 0) if (a > b) z = a; else z = b; if (n > 0) if (a > b) z = a; else z = b; z = ? z = 20 z = 3

12 Ambiguity Removal if (n > 0) if (a > b) z = a; else z = b;
} else z = b; if (n > 0) if (a > b) z = a; else z = b; if (n > 0){ if (a > b) z = a; else z = b; }

13 Programming Language  C Types, Operators and Expressions
Else-If Statement

14 Else-If Statement option if (expression) statement
else if (expression) else option

15 Example: Binary Search
int binsearch(int x, int v[], int n); 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] 6  binsearch(137, v, 11) 9  binsearch(201, v, 11) -1  binsearch(45, v, 11)

16 Example: Binary Search
binsearch(25, v, 11) Example: Binary Search low <= high mid = (low + high) / 2 = 5 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] low = v[mid] = 125 > 25 mid = high =

17 Example: Binary Search
binsearch(25, v, 11) Example: Binary Search v[] low = 1 1 5 2 9 v[mid] = 125 > 25 3 25 high = 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

18 Example: Binary Search
binsearch(25, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 2 low = 1 1 5 mid = 2 9 v[mid] = 9 < 25 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

19 Example: Binary Search
binsearch(25, v, 11) Example: Binary Search v[] 1 1 5 mid = 2 9 v[mid] = 9 < 25 low = 3 25 high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

20 Example: Binary Search
3  binsearch(25, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 3 1 1 5 2 9 v[mid] = 25 == 25 mid = low = 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

21 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search low <= high mid = (low + high) / 2 = 5 1 5 9 25 80 125 137 140 180 201 400 2 3 4 6 7 8 10 v[] low = v[mid] = 125 > 25 mid = high =

22 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search v[] low = 1 1 5 2 9 v[mid] = 125 > 45 3 25 high = 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

23 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 2 low = 1 1 5 mid = 2 9 v[mid] = 9 < 45 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

24 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 mid = 2 9 v[mid] = 9 < 45 low = 3 25 high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

25 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 3 1 1 5 2 9 v[mid] = 25 < 45 mid = low = 3 25 high = 4 80 5 125 6 137 7 140 8 180 9 201 10 400

26 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 2 9 v[mid] = 25 < 45 mid = 3 25 low= high = 4 80 low = mid + 1 5 125 6 137 7 140 8 180 9 201 10 400

27 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search low <= high v[] mid = (low + high) / 2 = 4 1 1 5 2 9 v[mid] = 80 > 45 3 25 low= high = 4 80 mid = 5 125 6 137 7 140 8 180 9 201 10 400

28 Example: Binary Search
binsearch(45, v, 11) Example: Binary Search v[] 1 1 5 2 9 v[mid] = 80 > 45 high = 3 25 low= 4 80 high = mid - 1 mid = 5 125 6 137 7 140 8 180 9 201 10 400

29 Example: Binary Search
-1  binsearch(45, v, 11) Example: Binary Search low <= high v[] 1 1 5 2 9 high = 3 25 low= 4 80 mid = 5 125 6 137 7 140 8 180 9 201 10 400

30 Example: Binary Search
/* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low <= high) { mid = (low+high)/2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else /* found match */ return mid; } return -1; /* no match */

31 Example: Binary Search

32 Exercises Consider the following grading table:
Write a program that reads students’ grades and prints out the corresponding class for each grade. Grade Class A B C D < F

33 Exercises Write a program to compute by bisection the square root of a positive integer N given by the user. The algorithm proceeds as follows: Start with N and 1 as the upper and lower bounds, and then find the midpoint of the two bounds. If the square of the midpoint is equal or very close to N, then output the midpoint as the answer and the algorithm terminates. If the square of the midpoint is greater than N, then let the upper bound be the midpoint; otherwise let the lower bound be the midpoint. Repeat the process until the two most recent estimates of the square root of N is within of each other. Output the last estimate as the answer and the algorithm terminates.

34 Programming Language  C Types, Operators and Expressions
Switch Statement

35 Switch Statement option Execution falls through if without break.
switch (expression) { case item1: statement1; break; case item2: statement2; case itemn: statementn; default: statement; } Execution falls through if without break. option

36 Example  switch (letter) { case 'A': numberofvowels++; break;
case 'E': case 'I': case 'O': case 'U': case ' ': numberofspaces++; default: numberofconsonants++; } switch (letter) { case 'A': case 'E': case 'I': case 'O': case 'U': numberofvowels++; break; case ' ': numberofspaces++; default: numberofconsonants++; }

37 Exercise Write a function escape(s, t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters.

38 Programming Language  C Types, Operators and Expressions
Loops – While and For

39 While Statement while (expression) statement
The statement is cyclically executed as long as the expression is evaluated non-zero. This cycle continues until expression becomes zero, at which point execution resumes after statement. while (expression) statement

40 for Statement for (expr1; expr2; expr3) statement Continuing check.
Loop variable(s) update Loop variable(s) initialization for (expr1; expr2; expr3) statement

41 While vs. For The choice between while and for is arbitrary, based on which seems clearer The for is usually used for a counter-like loop expr1; while (expr2) { statement expr3; } while (expression) statement for (expr1; expr2; expr3) statement

42 While vs. For any of them can be omitted while (expression) statement
for (expr1; expr2; expr3) statement

43 Infinite Loops while(1){ } for(; ;){ } while (expression) statement
for (expr1; expr2; expr3) statement

44 Infinite Loops How to break the loop? while(1){ } for(; ; ;){ }
if(…) break; or if(…) return; if(…) break; or if(…) return; while (expression) statement for (expr1; expr2; expr3) statement

45 Example: Bubble Sort

46 Example: Bubble Sort

47 Example: Bubble Sort (I)
void BubbleSort(int data[], int n) { int tmp, i, j; for(i=0; i<n-1; i++) for(j=0; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; }

48 Example: Bubble Sort (II)
void BubbleSort(int data[], int n) { int tmp, i, j, sorted; for(i=0, sorted=FALSE; !sorted && i<n-1; i++) for(j=0, sorted=TRUE; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; sorted = FALSE; } void BubbleSort(int data[], int n) { int tmp, i, j; for(i=0; i<n-1; i++) for(j=0; j<n-i-1; j++) if(data[j] > data[j+1]){ tmp = data[j]; data[j] = data[j+1]; data[j+1] = tmp; }

49 Exercises Modify the BubbleSort function such that its outer loop is a while statement. Verify your result. Modify the BubbleSort function such that its all loops are a while statement. Verify your result.

50 Programming Language  C Types, Operators and Expressions
Do-While Statement

51 Do-While Statement do statement while (expression);

52 Example: itoa /* itoa: convert n to characters in s */
void itoa(int n, char s[]) { int i, negative; n = (negative = (n < 0)) ? –n : n; /* record sign */ /* make n positive */ i = 0; do { /* generate digits in reverse order */ s[i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (negative) s[i++] = '-'; s[i] = '\0'; reverse(s); }

53 Exercises Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) formats s as a hexadecimal integer in s. Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough.

54 Programming Language  C Types, Operators and Expressions
Break and Continue

55 break and continue A break causes the innermost enclosing loop (for, while, do) or switch to be exited immediately. A continue causes the next iteration of the enclosing for, while, or do loop to begin.

56 Example: (break) Remove Trailing Blanks
/* trim: remove trailing blanks, tabs, newlines */ int trim(char s[]) { int n; for (n = strlen(s)-1; n >= 0; n--) if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n') break; s[n+1] = '\0'; return n; }

57 Example: (continue) Remove Factor 2
/* trim: remove all of factor 2 in int array */ int remove2(int s[], int n) { int i, nchange; for (i = 0, nchange = 0; i < n; i++){ if(s[i] & 1 || s[i] == 0) continue; while(!(s[i] & 1)) s[i] /= 2; nchange++ } return nchange;

58 Programming Language  C Types, Operators and Expressions
Goto and Labels

59 The goto and Labeled Statements
labeled-statement jump-statement jump-statement : goto identifier ; labeled-statement : identifier : statement

60 The goto Statement The goto statement performs an unconditional transfer of control to the named label. The label must be in the current function. Don’t use goto frequently appropriate case  error handling

61 Example: goto void main() { int i, j; for ( i = 0; i < 10; i++ ){
printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ){ printf( "Inner loop executing. i = %d j = %d\n", i, j ); if ( j == 1 && i==5 ) goto stop; } /* This message does not print: */ printf( "Loop exited. i = %d j = %d\n", i, j ); stop: printf( "Jumped to stop. i = %d j = %d\n", i, j );

62 Example: goto void main() { int i, j; for ( i = 0; i < 10; i++ ){
printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ){ printf( "Inner loop executing. i = %d j = %d\n", i, j ); if ( j == 1 && i==5 ) goto stop; } /* This message does not print: */ printf( "Loop exited. i = %d j = %d\n", i, j ); stop: printf( "Jumped to stop. i = %d j = %d\n", i, j );

63 Exercise Modify the above program as a gotoless program.

64 Example: Using Label for Error Handling
for( p = 0; p < NUM_PATHS; ++p ){ NumFiles = FillArray( pFileArray, pszFNames ) for( i = 0; i < NumFiles; ++i ){ if( (pFileArray[i] = fopen( pszFNames[i], "r" )) == NULL ) goto FileOpenError; // Process the files that were opened. } FileOpenError: printf( "Fatal file open error. Processing interrupted.\n" );


Download ppt "Programming Language  C Control Flow"

Similar presentations


Ads by Google