C Program Design C Program Control

Preview:

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

C Program DesignC 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 DesignC Program Control

Basic Problem-Solving Techniques

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

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

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

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

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

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

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

C Program DesignC Program Control

Assignment

Statements

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

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

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

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

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

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

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)

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

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

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

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.

C Program DesignC Program Control

If-Else-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

If-Else Statement

if (expression)

statement1

else

statement2

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

If-Else Statement

if (expression)

statement1

else

statement2

expressionstartstart

endend

expressionexpression

statement1statement1 statement2

statement2

true false

option

If-Statement

if (expression)

statement

expressionstartstart

endend

expressionexpression

statementstatement

true

false

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

Shortcut

if(expression != 0) ...

if(expression) ...

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;

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

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

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

C Program DesignC Program Control

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”

Else-If Statement

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

option

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

C Program DesignC Program Control

While-Statement

While-Statement

while(expression)

statement

expressionstartstart

endendexpressionexpression

statementstatement

true

false

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

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

}}

C Program DesignC Program Control

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

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

}

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

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

}

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

}

範例:本利和求算

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

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

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

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

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

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

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

C Program DesignC Program Control

Do-While-Statement

Do-While-Statement

do

statement

while (expression);

startstart

endendexpressionexpression

true

false

statementstatement

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

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

C Program DesignC Program Control

Switch-Statement

Switch Statement

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

option

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.

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.

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

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

C Program DesignC Program Control

Break and

Contiune

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.

範例#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 倍數之正整數加總,直至用戶輸入一負數為止

範例#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 倍數之正整數加總,直至用戶輸入一負數為止

Recommended