C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques...

67
C Program Design C Program Control 主主主 主主主

Transcript of C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques...

Page 1: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

主講人:虞台文

Page 2: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

Page 3: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Basic Problem-Solving Techniques

Page 4: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

Page 5: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

Page 6: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Control Structures

Bohm and Jacopini– All programs can be written in terms of 3 contro

l structures Sequence structures: Built into C. Programs executed

sequentially by default Selection structures: C has three types: if, if…else, an

d switch Repetition structures: C has three types: while, do…w

hile and for

Page 7: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

Page 8: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Example: Pseudocode Algorithm toSolve the Class Average Problem

Set grade counter to oneSet total to zero

While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

輸入十位學生成績,並求其平均變數: count, total, grade, average變數: count, total, grade, average

Page 9: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Example: Pseudocode Algorithm toSolve the Class Average Problem

Set grade counter to oneSet total to zero

While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

輸入十位學生成績,並求其平均變數: count, total, grade, average變數: count, total, grade, average

Initialization Phase

Processing Phase

Termination Phase

Page 10: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

#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 oneSet total to zero

While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

Set grade counter to oneSet total to zero

While grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by tenPrint the class average

變數: count, total, grade, average變數: count, total, grade, average

Page 11: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Assignment

Statements

Page 12: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

#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

Page 13: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

#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

int counter = 1; /* number of grade to be entered next */int total = 0; /* sum of grades input by user */

Page 14: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

#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 statement

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

Page 15: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

#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 statement

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

Page 16: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

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

Page 17: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

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

Page 18: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Assignment Operators

Assignment operators abbreviate assignment expressions, e.g.,c = c + 3;

can be abbreviated asc += 3;

Statements of the formvariable = variable operator expression;

can be rewritten asvariable operator= 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)

Page 19: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Assignment Operators

Assignment operator

Sample expression

Explanation Assigns

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;

+= c += 7 c = c + 7 10 to c

-= d -= 4 d = d - 4 1 to d

*= e *= 5 e = e * 5 20 to e

/= f /= 3 f = f / 3 2 to f

%= g %= 9 g = g % 9 3 to g

Page 20: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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

Page 21: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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 asc++; printf( “%d”, c );

Page 22: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Increment and Decrement Operators

Operator Sample expression Explanation

++ ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

Page 23: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

If-Else-Statement

Page 24: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Statements

Simple Statementslower = 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

Page 25: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

If-Else Statement

if (expression)

statement1

else

statement2

Page 26: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

If-Else Statement

if (expression)

statement1

else

statement2

expression

If expression is evaluated to true (nonzero),

statement1 is executed;

otherwise, statement2 is executed.

If expression is evaluated to true (nonzero),

statement1 is executed;

otherwise, statement2 is executed.

startstart

endend

expressionexpression

statement1statement1 statement2

statement2

true false

Page 27: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

If-Else Statement

if (expression)

statement1

else

statement2

expressionstartstart

endend

expressionexpression

statement1statement1 statement2

statement2

true false

option

Page 28: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

If-Statement

if (expression)

statement

expressionstartstart

endend

expressionexpression

statementstatement

true

false

Page 29: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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" );}

if ( grade >= 60 )

printf( "Passed.\n" );

else {

printf( "Failed.\n" );

printf( "You must take this course again.\n" );}

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");

Page 30: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Shortcut

if(expression != 0) ...

if(expression) ...

Page 31: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Example Codes

int total, count, average;. . . . . . . . . . . . .if ( count != 0 ) average = total / count;else average = 0;

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;. . . . . . . . . . . . .if ( count ) average = total / count;else average = 0;

Page 32: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Ternary Conditional Operator (?:)

int total, count, average;. . . . . . . . . . . . .if ( count != 0 ) average = total / count;else average = 0;

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;. . . . . . . . . . . . .if ( count ) average = total / count;else average = 0;

int total, count, average;. . . . . . . . . . . . .average = count != 0 ? total / count : 0;

int total, count, average;. . . . . . . . . . . . .average = count != 0 ? total / count : 0;

int total, count, average;. . . . . . . . . . . . .average = count ? total / count : 0;

int total, count, average;. . . . . . . . . . . . .average = count ? total / count : 0;

condition ? value if true : value if false

Page 33: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Dangling Else Problem

if (n > 0) if (a > b) z = a; else z = b;

if (n > 0) if (a > b) z = a; else z = b;

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

Page 34: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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;

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;}

Page 35: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Else-If-Statement

Page 36: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Nested If-Else Statements

If student’s grade is greater than or equal to 90Print “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”

Page 37: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Else-If Statement

if (expression) statement else if (expression) statement else if (expression) statement else if (expression) statement else statement

option

Page 38: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Example

If student’s grade is greater than or equal to 90Print “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 student’s grade is greater than or equal to 90Print “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");

elseprintf("F");

if (grade >= 90)printf("A");

else if (grade >= 80)printf("B");

else if (grade >= 70)printf("C");

else if (grade >= 60)printf("D");

elseprintf("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");

Page 39: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

While-Statement

Page 40: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

While-Statement

while(expression)

statement

expressionstartstart

endendexpressionexpression

statementstatement

true

false

Page 41: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#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);

}

#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);

}

從一非負的整數中移除因子 5

Page 42: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例: 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);

}}

#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);

}}

Page 43: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

For-Statement

Page 44: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

For-Statement

for (expr1; expr2; expr3)

statement

for (expr1; expr2; expr3)

statement

Loop variable(s) initializatio

n

Loop variable(s) initializatio

n

Continuing check.

Continuing check.

Loop variable(s) update

Loop variable(s) update

Page 45: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例:華氏攝氏59 ( 32)C F

#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;

for(fahr = 0; fahr <= 300; fahr += 20) { celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n", fahr, celsius);}

}

Page 46: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

While vs. For

while (expression)

statement

while (expression)

statement

for (expr1; expr2; expr3)

statement

for (expr1; expr2; expr3)

statement

expr1;

while (expr2) {

statement

expr3;

}

expr1;

while (expr2) {

statement

expr3;

}

The choice between while and for is arbitrary, based on which seems clearer

The for is usually used

for a counter-like loop

Page 47: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例: While vs. For

#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;}

}

#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;}

}

#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;

for(fahr = 0; fahr <= 300; fahr += 20) { celsius = 5 * (fahr-32) / 9; printf("%d\t%d\n", fahr, celsius);}

}

Page 48: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例: 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);}

}

#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);}

}

Page 49: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例:本利和求算

本利和求算公式 a(n) = p(1 + r)n

a(n): n 年後之本利和 p: 本金 r: 年利率 n: 儲存時間 ( 年 )

某君現有本金 1000.00 元,年利率設為 0.05 ,列出該君一至十年後之本利和。

Page 50: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例:本利和求算/* 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 */}

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

本利和求算公式 a(n) = p(1 + r)n

pow(1+r, n)

Page 51: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例:本利和求算/* 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 */}

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

本利和求算公式 a(n) = p(1 + r)n

pow(1+r, n)

Page 52: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

More on Loop-Variables Initialization and Update

for (i = 0, j = 0; j + i <= 10; j++, i++) printf( "%d\n", j + i );

Multiple Loop variables

initialization

Multiple Loop variables

initialization

Multiple loop variables

update

Multiple loop variables

update

Page 53: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

More on Loop-Variables Initialization and Update

for(number = 2, sum = 0; number <= 100; number += 2)

sum += number; // simple statement

for(number = 2, sum = 0; number <= 100; number += 2)

sum += number; // simple statement

for(number = 2, sum = 0; number <= 100; sum += number, number += 2)

; // null statement

for(number = 2, sum = 0; number <= 100; sum += number, number += 2)

; // null statement

Page 54: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Do-While-Statement

Page 55: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Do-While-Statement

do

statement

while (expression);

startstart

endendexpressionexpression

true

false

statementstatement

Page 56: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>main(){ int posnum, rev; do{ //輸入大於 0的正整數 printf("Input an integer:"); scanf("%d", &posnum); } while (posnum <= 0);

printf("The reverse is:");

while (posnum != 0){ //將正整數倒過來輸出 rev = posnum % 10; //取出 posnum的個位數 posnum /= 10; printf("%d", rev); } printf("\n\n");}

#include <stdio.h>main(){ int posnum, rev; do{ //輸入大於 0的正整數 printf("Input an integer:"); scanf("%d", &posnum); } while (posnum <= 0);

printf("The reverse is:");

while (posnum != 0){ //將正整數倒過來輸出 rev = posnum % 10; //取出 posnum的個位數 posnum /= 10; printf("%d", rev); } printf("\n\n");}

將一大於零的整數反向顯示

Page 57: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Switch-Statement

Page 58: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Switch Statement

switch (expression) {case item1: statement1; break;case item2: statement2; break;. . . . . . . .case itemn: statementn; break;default: statement; break;}

option

Page 59: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Switch Statement

switch (expression) {case item1: statement1; break;case item2: statement2; break;. . . . . . . .case itemn: statementn; break;default: statement; break;}

option

The result of the expression is an

integer.

The result of the expression is an

integer.

Integer constants.Integer constants.Integer constants.Integer constants.Integer constants.Integer constants.

Page 60: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

Switch Statement

switch (expression) {case item1: statement1; break;case item2: statement2; break;. . . . . . . .case itemn: statementn; break;default: statement; break;}

option

Execution falls through if without break.

Page 61: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

Page 62: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

Page 63: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : case 2 : printf("few"); break; case 3 : case 4 : case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : case 2 : printf("few"); break; case 3 : case 4 : case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

#include <stdio.h>

main(){ int number; printf("How many apples do you have?"); scanf("%d", &number);

printf("You have "); switch(number) { case 0 : printf("none"); break; case 1 : printf("few"); break; case 2 : printf("few"); break; case 3 : printf("several"); break; case 4 : printf("several"); break; case 5 : printf("several"); break; default : printf("many"); break; } printf(" apple(s).\n");}

Page 64: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

C Program DesignC Program Control

Break and

Contiune

Page 65: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

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.

Page 66: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>

main(){ int countAll=0; // # pos int entered int countValid=0; // # pos int without factor 5 int sum=0; // the sum of integers without factor 5 int value; // int entered by user

while(1){ printf("Enter the %dth number or -1 to end:", countAll+1); scanf("%d", &value); if(value < 0) // exit the loop break; countAll++; if(value % 5 == 0) // has factor 5 continue; countValid++; sum += value; } printf("\nYou entered %d positive integers;\n“ "%d of them are without factor 5;\n" "and their sum is %d.\n\n", countAll, countValid, sum);}

#include <stdio.h>

main(){ int countAll=0; // # pos int entered int countValid=0; // # pos int without factor 5 int sum=0; // the sum of integers without factor 5 int value; // int entered by user

while(1){ printf("Enter the %dth number or -1 to end:", countAll+1); scanf("%d", &value); if(value < 0) // exit the loop break; countAll++; if(value % 5 == 0) // has factor 5 continue; countValid++; sum += value; } printf("\nYou entered %d positive integers;\n“ "%d of them are without factor 5;\n" "and their sum is %d.\n\n", countAll, countValid, sum);}

將用戶從標準輸入裝置輸入非 5 倍數之正整數加總,直至用戶輸入一負數為止

Page 67: C Program Design C Program Control 主講人:虞台文. Content Basic problem-solving techniques Assignment Statements Control Statements – If-Else-Statement – Else-If-Statement.

範例#include <stdio.h>

main(){ int countAll=0; // # pos int entered int countValid=0; // # pos int without factor 5 int sum=0; // the sum of integers without factor 5 int value; // int entered by user

while(1){ printf("Enter the %dth number or -1 to end:", countAll+1); scanf("%d", &value); if(value < 0) // exit the loop break; countAll++; if(value % 5 == 0) // has factor 5 continue; countValid++; sum += value; } printf("\nYou entered %d positive integers;\n“ "%d of them are without factor 5;\n" "and their sum is %d.\n\n", countAll, countValid, sum);}

#include <stdio.h>

main(){ int countAll=0; // # pos int entered int countValid=0; // # pos int without factor 5 int sum=0; // the sum of integers without factor 5 int value; // int entered by user

while(1){ printf("Enter the %dth number or -1 to end:", countAll+1); scanf("%d", &value); if(value < 0) // exit the loop break; countAll++; if(value % 5 == 0) // has factor 5 continue; countValid++; sum += value; } printf("\nYou entered %d positive integers;\n“ "%d of them are without factor 5;\n" "and their sum is %d.\n\n", countAll, countValid, sum);}

將用戶從標準輸入裝置輸入非 5 倍數之正整數加總,直至用戶輸入一負數為止