Beruflich Dokumente
Kultur Dokumente
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; }
if if/else switch
C has three repetition structures:
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
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
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
Meaning
AND OR NOT
10
Operator Precedence
Operator Function calls ! + - & (unary operators) * / % + < <= >= > == != && || =
Precedence highest
lowest
11
C code:
if ( grade >= 60 ) printf( "Passed\n"); else printf( "Failed\n");
12
The ifelse Selection Statement Flow chart of the ifelse selection statement
true
print Passed
13
14
15
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
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
*/ YES
21
22
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
. . . statementn;
25
How it works
26
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)
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
statement1; statement2;
. . . statementn;
}
30
The for statement designates a place for each of these components, resulting in a more compact code for counting loops.
31
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
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
Year 1 2 3 4 5 6 7 8 9 10
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
34
/* 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
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
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
43
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
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); }
46
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
50