Sie sind auf Seite 1von 50

1

Program Control: Selection and Repetition

Control Structures Control structures control the flow of execution in a program. Statements are organized into three kinds of control structures to control execution flow:
sequence selection repetition

Sequential Execution Statements are executed one after the other in the order they are written in the curly braces:
{ statement_1; statement_2; . . . statement_n; }

Control Structures Transfer of control


Direction of the program can be changed using selection and also repetition structure. C has three selection structures:

if if/else switch
C has three repetition structures:

while do/while for

The if Selection Statement Selection structure:


Used to choose among alternative courses of action

Syntax:
if (condition) statement;

If condition true
statement executed and program goes on to next statement If false, statement is ignored and the program goes onto the next statement Indenting makes programs easier to read
C ignores whitespace characters

The if Selection Statement


if statement is a single-entry/single-exit structure
if ( grade >= 60 ) printf( "Passed \n" );

grade >= 60

true

print Passed

false

Conditions Condition is an expression whose evaluation produces either FALSE or TRUE result.
FALSE is represented by zero TRUE is represented by non-zero

Most conditions for comparisons have the form:


Variable equality-operator variable Variable equality-operator constant Variable relational-operator variable Variable relational-operator constant

Equality and Relational Operators


Standard algebraic equality operator or relational operator Equality Operators
= == != x == y x != y x is equal to y x is not equal to y

C equality or Example of C relational operator condition

Meaning of C condition

Relational Operators
> < >= <= > < >= <= x>y x<y x >= y x <= y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y

Logical Operators

A logical operator is used to combine conditions


Operator
&& || !

Meaning
AND OR NOT

10

Operator Precedence

Operator Function calls ! + - & (unary operators) * / % + < <= >= > == != && || =

Precedence highest

lowest

11

The ifelse Selection Statement


Syntax:
if (condition) statement_T; else statement_F;

C code:
if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n");

Ternary conditional operator (?:)


Takes three arguments (condition, value if true, value if false) Our pseudocode could be written:
printf( "%s\n", grade >= 60 ? "Passed" : "Failed" );

Or it could have been written:


grade >= 60 ? printf( Passed\n ) : printf( Failed\n );

12

The ifelse Selection Statement Flow chart of the ifelse selection statement

false grade >= 60 print Failed

true

print Passed

Nested ifelse statements


Test for multiple cases by placing ifelse selection statements inside ifelse selection statement Once condition is met, rest of statements skipped Deep indentation usually not used in practice

13

The ifelse Selection Statement Compound statement:


Set of statements within a pair of braces Example:
if ( grade >= 60 ) printf( "Passed.\n" ); else { printf( "Failed.\n" ); printf( "You must take this course again.\n" ); }

Without the braces, the statement


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

would be executed automatically

14

Nested if/else Statements


Test for multiple cases by placing if/else selection structures inside if/else selection structures Once condition is met, rest of statements skipped statement_1; if (condition_1) { statement_2; statement_3; } else if(condition_2) { statement_4; statement_5; } . . else statement_n; statement_m;

15

Nested if/else Statements

if (road_status == S) if (temperature > 0) { printf(Wet roads ahead\n); printf(Stopping time doubled\n); } else { printf(Icy roads ahead\n); printf(Stopping time quadrupled\n); } else printf(Drive carefully!\n);

16

switch Statement To select one of several alternatives. Selection is based on the value of an expression. Expression could be a single value. The type of expression can be either int or char type, but not double.

17

switch Statement

Syntax:
switch (expression){ case const-expr:
statements; break; case const-expr: statements; break;

. .
.

case const-expr:
statements; break; default: statements; break; }

18

switch Statement

true case a false true case b false . . . case b action(s) break case a action(s) break

true case z false default action(s) case z action(s) break

19

switch Statement
switch (class) { case 'B': case 'b': printf("Battleship\n"); break; case 'C': case 'c': printf("Cruiser\n"); break; case 'D': case 'd': printf("Destroyer\n"); break; case 'F': case 'f': printf("Frigate\n"); break; default: printf("Unknown ship class %c\n", class); }

20

Example for Logical Assignment


int age; char gender; int senior_citizen; senior_citizen = 1; /* Set senior citizen */ scanf(%d, &age); senior_citizen = (age >= 65) /* Is it right?

*/ YES

21

Example for Logical Assignment


int in_range; int is_letter, is_even; int n; char ch; in_range = (n> -10 && n < 10); is_letter = (A <= ch && ch <= Z) || (a <= ch && ch <= z); is_even = (n % 2 == 0) is_even = (n % 2) ? 0 : 1

22

Repetition in Programs Most programs contain repetition or looping.

A loop is a group of instructions (or statements) that the program executes repeatedly while looprepetition condition remains true.

23

Types of Loops In a counting loop, we know in advance the number of loop repetition needed to solve the problem. An example is calculating N!. In a conditional loop, it is not known in advance how many times the loop will be executed.

24

while Statement Syntax:


while (loop repetition condition) statement; OR while (loop repetition condition) { statement1; statement2;

. . . statementn;

25

Implementation With the while Statement


loop repetition condition initialization test update counter = 0; while (counter < N) { loop body printf(*); counter = counter + 1; } counter=0 loop exit false counter<N true printf (*) counter+=1 initialization test

How it works

The loop is iterated N times! The loop is iterated N times!

26

Example: Calculating Factorial Nfactorial=1; counter=1; while (counter<=N) { Nfactorial=Nfactorial*counter; counter=counter+1; }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

/* Fig. 3.6: fig03_06.c Class average program with counter-controlled repetition */ #include <stdio.h> /* function main begins program execution */ int main() { int counter; /* number of grade to be entered next */ int grade; int total; /* grade value */ /* sum of grades input by user */

27

Outline
fig03_06.c (Part 1 of 2)

int average; /* average of grades */ /* initialization phase */ total = 0; /* initialize total */ counter = 1; /* initialize loop counter */ /* processing phase */ while ( counter <= 10 ) { scanf( "%d", &grade ); total = total + grade; counter = counter + 1; } /* end while */ /* loop 10 times */ /* read grade from user */ /* add grade to total */ /* increment counter */ printf( "Enter grade: " ); /* prompt for input */

Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

25 26 27 28 29 30 31 32

/* termination phase */ average = total / 10; /* display result */ printf( "Class average is %d\n", average ); return 0; /* indicate program ended successfully */ /* integer division */

28

Outline
fig03_06.c (Part 2 of 2)

33 } /* end function main */

Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Class

grade: 98 grade: 76 grade: 71 grade: 87 grade: 83 grade: 90 grade: 57 grade: 79 grade: 82 grade: 94 average is 81

Program Output

Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

29

for Statement Syntax:


for (initialization; loop repetition condition; update) statement; OR for (initialization; loop repetition condition; update) {

statement1; statement2;

. . . statementn;
}

30

Implementation With the for Statement


initialization loop repetition update expression condition count++)

for (count=0; count<N; printf(*);

Counting loops have three loop control statements:


Initialization of the loop control variable. Test of the loop repetition condition. Update of the loop variable.

The for statement designates a place for each of these components, resulting in a more compact code for counting loops.

31

Implementation With the for Statement


Remark: The for statement is a special case of the while statement. Any for loop can be rewritten as a while loop. Most programmers prefer the for statement to implement a counting loop.

for (expr1; expr2; expr3) statement

expr1; while (expr2) { statement; expr3; }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

/* Fig. 4.6: fig04_06.c Calculating compound interest */ #include <stdio.h> #include <math.h>

32

Outline
fig04_06.c (Part 1 of 2)

/* function main begins program execution */ int main() { double amount; double rate = .05; int year; /* amount on deposit */ /* interest rate */ /* year counter */ double principal = 1000.0; /* starting principal */

/* output table column head */ printf( "%4s%21s\n", "Year", "Amount on deposit" ); /* calculate 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.2f\n", year, amount ); } /* end for */

Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

27 28

return 0; /* indicate program ended successfully */

33

Outline
Amount on deposit 1050.00 1102.50 1157.63 1215.51 1276.28 1340.10 1407.10 1477.46 1551.33 1628.89

29 } /* end function main */

Year 1 2 3 4 5 6 7 8 9 10

fig04_06.c (Part 2 of 2) Program Output

Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

34

General Conditional Loop:


The loop continues to execute as long as a repetition condition remains true. Example:

/* Multiply data while product remains less than 1000. */ product = 1; /* initialization */ while (product < 1000) { printf(%d\n, product); /* Display product so far */ printf(Enter next item > ); scanf(%d, &item); product = product * item; /* update product */ } Running product Running product

35

Input Validation Loop:


The loop continues to read input data until the data variable is in the accepted range. Example: Suppose a programmer wishes to ask for a number and keeps asking until a valid positive number is supplied by the user.

printf(Enter number of items> ); scanf(%d, &num_item); /* initialize number of item */ while (num_item < 0) { printf(Invalid number; enter a positive number>); scanf(%d, &num_item); /* update */ }

36

Sentinel-controlled Loops
Many programs with loops input data items each time the loop body is repeated. In most cases, the number of data items is not known in advance. One way to signal the end data and terminate the loop execution is to use a sentinel value. A sentinel must be a value that could not occur as data.

37

Sentinel-controlled Loops
Example:
/* computes the sum of a list of exam scores */ #include <stdio.h> #define SENTINEL 99 int main(void) { int sum = 0; /* outputsum of scores input */ int score; /* inputcurrent score */ printf(Enter first score (or %d to quit)>,SENTINEL); scanf(%d, &score); while (score != SENTINEL) { Running sum Running sum sum += score; printf(Enter next score (%d to quit)>,SENTINEL); scanf(%d, &score); /* Get next score */ } printf(\n Sum of exam scores is %d\n, sum); return 0; }

38

Sentinel-controlled Loops
Any conditional loop can also be implemented by using the for statement. Most programmers prefer the while statement to implement conditional loops. The previous example could also be implemented with the for statement though it seems quite bizarre.

for (scanf(%d,&score); score!=SENTINEL; scanf(%d, &score)) { sum += score; printf(Enter next score (%d to quit)>,SENTINEL); }

39

Nested Loops Loops may be nested just like other control structures (e.g. the if statement). A nested loop consists of an outer loop with one or more inner loops.

40

Example With the for Statement

Compute i*j
i=0 j=0

N M

sum = 0; for (i=0; i<=N; i++) { for (j=0; j<=M; j++) { sum += i*j; } } printf(The total sum is %d, sum);

sum = 0; for (i=0; i<=N; i++) OR for (j=0; j<=M; j++) sum += i*j; printf(The total sum is d, sum);

41

Example With the for Statement Suppose that we also want to compute the inner sums.
sum = 0; for(i=0; i<=N; i++) { inner_sum = 0; for(j=0; j<=M; j++) inner_sum += i*j; printf(The inner sum %d is %d.\n,i,inner_sum); sum += inner_sum; } printf(The total sum is %d., sum); For N=2; M=2, the output is: The inner sum 0 is 0. The inner sum 1 is 3. The inner sum 2 is 6. The total sum is 9.

42

Example With the while Statement


Continue = Y; while (Continue == Y || Continue == y) { company_total = 0; printf(At any time, type 99 when all data is entered.); printf(\n Enter the first salesman\s total>); scanf(%lf,&individual_total); while (individual_total != -99) { company_total += individual_total; printf(Enter the next salesman\s total>); scanf(%lf,&individual_total); } printf(The company made %f in sales today.\n, company_total); printf(Type Y to continue, anything else to quit>); scanf(%c,&Continue); } Likewise the for and while loops can be nested one inside the other.

43

do-while Statement Syntax:


do { statament1; statement2; . . } while (condition);
Note that there is Note that there is aasemi-colon here. semi-colon here.

The for and while statements both evaluate the loop repetition condition before the execution of the loop body. Sometimes we may need to check the repetition condition at the end of the loop body. Such a loop can be created by the do-while statement:

44

do-while Statement
With the do-while statement, first the loop is executed and then the condition is tested. If the condition is true, the loop body is repeated. Therefore, a do-while loop is always executed at least once. Example: Entering a valid letter from the prompt:
do { printf(Enter a letter from A through Z>); scanf(%c, &letter_choice); } while (letter_choice<A || letter choice>Z);

Since the user must enter at least one data character, the dowhile is an ideal statement to implement this loop.

45

Alternative With the while Statement

printf(Enter a letter from A through Z>); scanf(%c, &letter_choice); while (letter_choice<A || letter_choice>Z) { printf(Enter a letter from A through Z>); scanf(%c, &letter_choice); }

Which one is better? Which one is better? Why? Why?

46

Common Loop Errors

The following code should sum up the values from 0 to n.


for (i=0, i<n; i++) sum += i;

The following code should ask for numbers and calculate a running sum until a sentinel value (-99) is encountered.
int sum; do { scanf(%d,&number); sum+=number; } while (number!=-99)

47

break and continue Statements A break statement can be used to exit from:
for while, and do/while

like in switch statement. A break statement causes the innermost enclosing loop to be exited immediately.

48

break and continue Statements continue causes the next iteration of the enclosing:
for while, or do/while

loop to begin when continue statement is used in while and do loops, this means that the condition part is executed immediately in the for loop, control passes to loop variable update step.

49

Example for continue


#include <stdio.h> int main(void){ int sum=0, n=1; while (n <= 10){ if ((n % 2) == 0) { n = n + 1; continue; } sum = sum + n; n = n + 1; } printf("sum = %d\n", sum); return(0); }

50

Reading Sections 3.1-3.10 and Chapter-4 of the textbook

Das könnte Ihnen auch gefallen