1 / 67

C Program Design C Program Control

C Program Design C Program Control. 主講人:虞台文. Content. Basic problem-solving techniques Assignment Statements Control Statements If-Else-Statement Else-If-Statement While-Statement For-Statement Do-While-Statement Switch-Statement Break and Continue. C Program Design C Program Control.

carol-york
Download Presentation

C Program Design C Program Control

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. C Program DesignC Program Control 主講人:虞台文

  2. Content • Basic problem-solving techniques • Assignment Statements • Control Statements • If-Else-Statement • Else-If-Statement • While-Statement • For-Statement • Do-While-Statement • Switch-Statement • Break and Continue

  3. C Program DesignC Program Control Basic Problem-Solving Techniques

  4. What and How? • Before writing a program: • Have a thorough understanding of the problem • Carefully plan an approach for solving it • While writing a program: • Know what “building blocks” are available • Use good programming principles

  5. Algorithms • Computation • All can be done by executing a series of actions in a specific order • Algorithm: procedure in terms of • Actions to be executed • The order in which these actions are to be executed • Program control • Specify order in which statements are to be executed

  6. Control Structures • Bohm and Jacopini • All programs can be written in terms of 3 control structures • Sequence structures: Built into C. Programs executed sequentially by default • Selection structures: C has three types: if, if…else, and switch • Repetition structures: C has three types: while, do…while and for

  7. Pseudocode • Artificial, informal language that helps us develop algorithms • Similar to everyday English • Not actually executed on computers • Helps us “think out” a program before writing it • Easy to convert into a program consisting only of executable statements

  8. 輸入十位學生成績,並求其平均 變數:count, total, grade, average Example: Pseudocode Algorithm toSolve the Class Average Problem Set grade counter to one Set total to zero While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average

  9. 輸入十位學生成績,並求其平均 變數:count, total, grade, average Example: Pseudocode Algorithm toSolve the Class Average Problem Set grade counter to one Set total to zero While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Initialization Phase Processing Phase Termination Phase

  10. 變數:count, total, grade, average Example:Pseudocode  C #include <stdio.h> main() { int counter; /* number of grade to be entered next */ int total; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* initialization phase */ counter = 1; total = 0; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */ Set grade counter to one Set total to zero While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average

  11. C Program DesignC Program Control Assignment Statements

  12. 輸入十位學生成績,並求其平均 Review: Class Average Problem #include <stdio.h> main() { int counter; /* number of grade to be entered next */ int total; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* initialization phase */ counter = 1; total = 0; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */ Assignment statements Assignment statements Assignment statement

  13. Variable Initialization #include <stdio.h> main() { int counter; /* number of grade to be entered next */ int total; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* initialization phase */ counter = 1; total = 0; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */ int counter = 1; /* number of grade to be entered next */ int total = 0; /* sum of grades input by user */ Assignment statements Assignment statements Assignment statement

  14. Abbreviations #include <stdio.h> main() { int counter; /* number of grade to be entered next */ int total; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* initialization phase */ counter = 1; total = 0; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */ int counter = 1; /* number of grade to be entered next */ int total = 0; /* sum of grades input by user */ total += grade; /* add grade to total */ counter += 1; /* increment counter */ Assignment statements Assignment statement

  15. Increment Operator (++) #include <stdio.h> main() { int counter; /* number of grade to be entered next */ int total; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* initialization phase */ counter = 1; total = 0; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total = total + grade; /* add grade to total */ counter = counter + 1; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */ int counter = 1; /* number of grade to be entered next */ int total = 0; /* sum of grades input by user */ total += grade; /* add grade to total */ counter += 1; /* increment counter */ counter++; /* increment counter */ Assignment statement

  16. New Version (I) #include <stdio.h> main() { int counter = 0; /* number of grade to be entered next */ int total = 0; /* sum of grades input by user */ int grade ; /* grade value */ int average; /* average of grades */ /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total += grade; /* add grade to total */ counter++; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */

  17. New Version (II) #include <stdio.h> main() { /* variables used */ int counter = 0, total = 0, grade, average; /* processing phase */ while ( counter <= 10 ) { /* loop 10 times */ printf( "Enter grade: " ); /* prompt for input */ scanf( "%d", &grade ); /* read grade from user */ total += grade; /* add grade to total */ counter++; /* increment counter */ } /* end while */ /* termination phase */ average = total / 10; /* integer division */ printf("Class average is %d\n", average); /* display result */ } /* end function main */

  18. Assignment Operators • Assignment operators abbreviate assignment expressions, e.g., c = c + 3; can be abbreviated as c += 3; • Statements of the form variable = variableoperatorexpression; can be rewritten as variableoperator=expression; • Examples of other assignment operators: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)

  19. Assignment Operators

  20. Increment and Decrement Operators • Increment operator (++) • Can be used instead of c+=1 • Decrement operator (--) • Can be used instead of c-=1 • Preincrement/predecrement • Operator is used before the variable (++c or --c) • Variable is changed before the expression it is in is evaluated • Postincrement/postdecrement • Operator is used after the variable (c++ or c--) • Expression executes before the variable is changed

  21. Increment and Decrement Operators • If c equals 5, then printf( "%d", ++c ); • Prints 6 printf( "%d", c++ ); • Prints 5 • In either case, c now has the value of 6 • When variable not in an expression • Preincrementing and postincrementing have the same effect ++c; printf( “%d”, c ); • Has the same effect as c++; printf( “%d”, c );

  22. Increment and Decrement Operators

  23. C Program DesignC Program Control If-Else-Statement

  24. Statements • Simple Statements 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

  25. If-Else Statement if (expression) statement1 else statement2

  26. start true expression false statement1 statement2 end If expression is evaluated to true (nonzero), statement1 is executed; otherwise, statement2 is executed. If-Else Statement if (expression) statement1 else statement2 expression

  27. If-Else Statement start if (expression) statement1 else statement2 expression true expression false statement1 statement2 option end

  28. start true expression false statement end If-Statement if (expression) statement expression

  29. Example Codes if ( grade >= 60 ) printf( "Passed\n"); if ( grade >= 60 ) printf( "Passed\n"); if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n"); if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n"); if ( grade >= 60 ) printf( "Passed.\n" ); else { printf( "Failed.\n" ); printf( "You must take this course again.\n" );}

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

  31. Example Codes int total, count, average; . . . . . . . . . . . . . if ( count != 0 ) average = total / count; else average = 0; int total, count, average; . . . . . . . . . . . . . if ( count ) average = total / count; else average = 0; 

  32. condition ? value if true : value if false Ternary Conditional Operator (?:) int total, count, average; . . . . . . . . . . . . . if ( count != 0 ) average = total / count; else average = 0; int total, count, average; . . . . . . . . . . . . . if ( count ) average = total / count; else average = 0;   int total, count, average; . . . . . . . . . . . . . average = count != 0 ? total / count : 0;  int total, count, average; . . . . . . . . . . . . . average = count ? total / count : 0;

  33. Dangling Else Problem 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

  34. Ambiguity Removal if (n > 0){ if (a > b) z = a; } 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; }

  35. C Program DesignC Program Control Else-If-Statement

  36. Nested If-Else Statements If student’s grade is greater than or equal to 90 Print “A”else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F”

  37. Else-If Statement if (expression) statement else if (expression) statement else if (expression) statement else if (expression) statement else statement option

  38. Example If student’s grade is greater than or equal to 90 Print “A”else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” if (grade >= 90) printf("A"); else if (grade >= 80) printf("B"); else if (grade >= 70) printf("C"); else if (grade >= 60) printf("D"); else printf("F"); if (grade >= 90) printf("A"); else if (grade >= 80) printf("B"); else if (grade >= 70) printf("C"); else if (grade >= 60) printf("D"); else printf("F");

  39. C Program DesignC Program Control While-Statement

  40. start expression false end true statement While-Statement while(expression) statement expression

  41. 範例 從一非負的整數中移除因子5 #include <stdio.h> main() { int number, numberRead; printf("Enter a nonnegative number:"); scanf("%d", & numberRead); number = numberRead; while (number % 5 == 0 && number > 0) number = number / 5; printf("Removing factor of 5 from %d, it becomes %d.\n", numberRead, number); }

  42. 範例:Forever Loop #include <stdio.h> main() { int number, numberRead; while(1){ printf("Enter a nonnegative number:"); scanf("%d", & numberRead); number = numberRead; while (number % 5 == 0 && number > 0) number = number / 5; printf("Removing factor of 5 from %d, it becomes %d.\n", numberRead, number); } }

  43. C Program DesignC Program Control For-Statement

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

  45. 範例:華氏攝氏 • #include <stdio.h> • /* print Fahrenheit-Celsius table • for fahr = 0, 20, ..., 300 */ • main() • { • int fahr, celsius; • for(fahr = 0; fahr <= 300; fahr += 20) { • celsius = 5 * (fahr-32) / 9; • printf("%d\t%d\n", fahr, celsius); • } • }

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

  47. 範例:While vs. For • #include <stdio.h> • /* print Fahrenheit-Celsius table • for fahr = 0, 20, ..., 300 */ • main() • { • int fahr, celsius; • for(fahr = 0; fahr <= 300; fahr += 20) { • celsius = 5 * (fahr-32) / 9; • printf("%d\t%d\n", fahr, celsius); • } • } • #include <stdio.h> • /* print Fahrenheit-Celsius table • for fahr = 0, 20, ..., 300 */ • main() • { • int fahr, celsius; • fahr = 0; • while(fahr <= 300) { • celsius = 5 * (fahr-32) / 9; • printf("%d\t%d\n", fahr, celsius); • fahr += 20; • } • }

  48. 範例: Counter Loop (I) • #include <stdio.h> • /* print Fahrenheit-Celsius table • for fahr = 0, 20, ..., 300 */ • main() • { • int fahr, celsius; • int i; • for(i = 0; i < 16; i++) { • fahr = i * 20; • celsius = 5 * (fahr-32) / 9; • printf("%d\t%d\n", fahr, celsius); • } • }

  49. 範例:本利和求算 a(n) = p(1 + r)n 本利和求算公式 a(n): n年後之本利和 p: 本金 r: 年利率 n: 儲存時間(年) 某君現有本金1000.00元,年利率設為0.05 ,列出該君一至十年後之本利和。

  50. 本利和求算公式 a(n) = p(1 + r)n pow(1+r, n) 範例:本利和求算 /* CompoundInterest.c */ #include <stdio.h> #include <math.h> main() { double amount; /* amount on deposit */ double principal = 1000.0; /* starting principal */ double rate = .05; /* annual interest rate */ int year; /* year counter */ /* output table column head */ printf( "%4s%21s\n", "Year", "Amount on deposit" ); /* calculate and output amount on deposit for each of ten years */ for ( year = 1; year <= 10; year++ ) { /* calculate new amount for specified year */ amount = principal * pow( 1.0 + rate, year ); /* output one table row */ printf( "%4d%21.2lf\n", year, amount ); } /* end for */ }

More Related