View
219
Download
0
Category
Preview:
Citation preview
8/2/2019 Comp 132 Notes 3 Program Control
1/50
1
Program Cont rol:Select ion and Repet it ion
8/2/2019 Comp 132 Notes 3 Program Control
2/50
2
Control Structures
Control structures control the flow of execution in
a program.
Statements are organized into three kinds ofcontrol structures to control execution flow:
sequence
selection
repetition
8/2/2019 Comp 132 Notes 3 Program Control
3/50
3
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;
}
8/2/2019 Comp 132 Notes 3 Program Control
4/50
4
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/whilefor
8/2/2019 Comp 132 Notes 3 Program Control
5/50
5
The i f Selection Statement Selection structure:
Used to choose among alternative courses of action
Syntax:
if(condition)
statement;
If condition t r u e
statement executed and program goes on to next statement
Iff a l s e , statement is ignored and the program goes onto
the next statement
Indenting makes programs easier to read
C ignores whitespace characters
8/2/2019 Comp 132 Notes 3 Program Control
6/50
6
The i f Selection Statement i f statement is a single-entry/single-exit structure
true
false
grade >= 60 print Passed
if ( grade >= 60 )
printf( "Passed \n" );
8/2/2019 Comp 132 Notes 3 Program Control
7/50
7
Conditions
Condition is an expression whose evaluation
produces eitherFALSE orTRUE result.
FALSE is represented by zero
TRUE is represented by non-zero
Most conditions for comparisons have the form:Variable equality-operatorvariable
Variable equality-operatorconstant
Variable relational-operatorvariableVariable relational-operatorconstant
8/2/2019 Comp 132 Notes 3 Program Control
8/50
8
Equality and Relational Operators
Standard algebraic equalityoperator or relational operator
C equality orrelational operator
Example of Ccondition
Meaning of C condition
Equality Operators
= == x == y x is equal to y ! = x ! = y x is not equal to y
Relational Operators
> > x > y x is greater than y < < x < y x is less than y >= >= x >= y x is greater than or equal to y
8/2/2019 Comp 132 Notes 3 Program Control
9/50
9
Logical Operators
A logical operator is used to combine conditions
Operator Meaning
&& AND
|| OR ! NOT
8/2/2019 Comp 132 Notes 3 Program Control
10/50
10
Operator Precedence
Operator Precedence
Function calls highest
! + - & (unary operators)
* / %
+ -< = >
== !=
&&||
= lowest
8/2/2019 Comp 132 Notes 3 Program Control
11/50
11
The i f e l s e Selection Statement Syntax:
if(condition)
statement_T;
elsestatement_F;
C code:i f ( g r a d e > = 6 0 )
p r i n t f ( " P a s s e d \ n " ) ;e l s e
p r i n t f ( " F a i l e d \ n " ) ;
Ternary conditional operator (? : ) Takes three arguments (condition, value ift r u e , value iff a l s e )
Our pseudocode could be written:p r i n t f ( " %s \ n " , g r a d e > = 6 0 ? " P a s s e d " : " F a i l e d " ) ;
Or it could have been written:g r a d e > = 6 0 ? p r i n t f ( P a s s e d \ n ) : p r i n t f (
F a i l e d \ n ) ;
8/2/2019 Comp 132 Notes 3 Program Control
12/50
12
The i f e l s e Selection Statement Flow chart of the i f e l s e selection statement
Nested i f e l s e statements
Test for multiple cases by placing i f e l s e selectionstatements inside i f e l s e selection statement
Once condition is met, rest of statements skipped
Deep indentation usually not used in practice
truefalse
print Failed print Passed
grade >= 60
8/2/2019 Comp 132 Notes 3 Program Control
13/50
13
The i f e l s e Selection Statement Compound statement:
Set of statements within a pair of braces
Example:
i f ( g r a d e > = 6 0 )
p r i n t f ( " P a s s e d . \ n " ) ;
e l s e {
p r i n t f ( " F a i l e d . \ n " ) ;
p r i n t f ( " Y o u mu s t t a k e t h i s c o u r s ea g a i n . \ n " ) ;
}
Without the braces, the statement
p r i n t f ( " Y o u mu s t t a k e t h i s c o u r s e
a g a i n . \ n " ) ;
would be executed automatically
8/2/2019 Comp 132 Notes 3 Program Control
14/50
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;
8/2/2019 Comp 132 Notes 3 Program Control
15/50
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);
8/2/2019 Comp 132 Notes 3 Program Control
16/50
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 eitherint orchar
type, but not double.
8/2/2019 Comp 132 Notes 3 Program Control
17/50
17
switch Statement
Syntax:switch (expression){
case const-expr:statements;
break;
case const-expr:statements;
break;
case const-expr:
statements;break;
default:statements;
break;
}
...
8/2/2019 Comp 132 Notes 3 Program Control
18/50
18
switch Statement
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
8/2/2019 Comp 132 Notes 3 Program Control
19/50
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);
}
8/2/2019 Comp 132 Notes 3 Program Control
20/50
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
8/2/2019 Comp 132 Notes 3 Program Control
21/50
21
Example for Logical Assignment
int in_range;
int is_letter, is_even;
int n;
char ch;
in_range = (n> -10 && n < 10);
is_even = (n % 2 == 0)
is_letter = (A
8/2/2019 Comp 132 Notes 3 Program Control
22/50
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 loop-
repetition condition remains true.
8/2/2019 Comp 132 Notes 3 Program Control
23/50
23
Types of Loops
In a counting loop, we know in advance the
number of loop repetition needed to solve theproblem. An example is calculating N!.
In a conditional loop, it is not known in advancehow many times the loop will be executed.
8/2/2019 Comp 132 Notes 3 Program Control
24/50
24
while Statement
Syntax:
while (loop repetition condition)statement;
OR
while (loop repetition condition) {
statement1;
statement2;
statementn;
}
...
8/2/2019 Comp 132 Notes 3 Program Control
25/50
25
Implementation With the while Statement
How it workscounter=0
counter
8/2/2019 Comp 132 Notes 3 Program Control
26/50
26
Example: Calculating Factorial
Nfactorial=1;
counter=1;
while (counter
8/2/2019 Comp 132 Notes 3 Program Control
27/50
Outline27
Outline
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
fig03_06.c (Part 1 of2)
1 / * F i g . 3 . 6 : f i g 0 3 _ 0 6 . c2 Cl a s s a v e r a g e p r o g r a m w i t h c o u n t e r - c o n t r o l l e d r e p e t i t i o n * /3 # i n c l u d e < s t d i o . h >4
5 / * f u n c t i o n ma i n b e g i n s p r o g r a m e x e c u t i o n * /6 i n t ma i n ( )7 {8 i n t c o u n t e r ; / * n u mb e r o f g r a d e t o b e e n t e r e d n e x t * /9 i n t g r a d e ; / * g r a d e v a l u e * /10 i n t t o t a l ; / * s u m o f g r a d e s i n p u t b y u s e r * /11 i n t a v e r a g e ; / * a v e r a g e o f g r a d e s * /12
13 / * i n i t i a l i z a t i o n p h a s e * /14 t o t a l = 0 ; / * i n i t i a l i z e t o t a l * /15 c o u n t e r = 1 ; / * i n i t i a l i z e l o o p c o u n t e r * /16
17 / * p r o c e s s i n g p h a s e * /18 wh i l e ( c o u n t e r < = 1 0 ) { / * l o o p 1 0 t i me s * /19 p r i n t f ( " E n t e r g r a d e : " ) ; / * p r o mp t f o r i n p u t * /20 s c a n f ( " %d " , & g r a d e ) ; / * r e a d g r a d e f r o m u s e r * /21 t o t a l = t o t a l + g r a d e ; / * a d d g r a d e t o t o t a l * /22 c o u n t e r = c o u n t e r + 1 ; / * i n c r e me n t c o u n t e r * /23 } / * e n d wh i l e * /24
2825 / * t e r mi n a t i o n p h a s e * /
8/2/2019 Comp 132 Notes 3 Program Control
28/50
Outline28
Outline
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
fig03_06.c (Part 2 of2)
Program Outputn t e r g r a d e : 9 8E n t e r g r a d e : 7 6E n t e r g r a d e : 7 1E n t e r g r a d e : 8 7E n t e r g r a d e : 8 3E n t e r g r a d e : 9 0E n t e r g r a d e : 5 7E n t e r g r a d e : 7 9
E n t e r g r a d e : 8 2E n t e r g r a d e : 9 4Cl a s s a v e r a g e i s 8 1
26 a v e r a g e = t o t a l / 1 0 ; / * i n t e g e r d i v i s i o n * /27
28 / * d i s p l a y r e s u l t * /29 p r i n t f ( " Cl a s s a v e r a g e i s %d \ n " , a v e r a g e ) ;30
31 r e t u r n 0 ; / * i n d i c a t e p r o g r a m e n d e d s u c c e s s f u l l y * /32
33 } / * e n d f u n c t i o n ma i n * /
29
8/2/2019 Comp 132 Notes 3 Program Control
29/50
29
for Statement
Syntax:
for (initialization; loop repetition condition; update)
statement;
OR
for (initialization; loop repetition condition; update) {statement1;
statement2;
statementn;
}
...
30
8/2/2019 Comp 132 Notes 3 Program Control
30/50
30
Implementation With the for Statement
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 ofthese components, resulting in a more compactcode for counting loops.
for (count=0; count
8/2/2019 Comp 132 Notes 3 Program Control
31/50
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;
}
321 / * F i g . 4 . 6 : f i g 0 4 _ 0 6 . c
8/2/2019 Comp 132 Notes 3 Program Control
32/50
OutlineOutline
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
fig04_06.c (Part 1 of 2)
2 Ca l c u l a t i n g c o mp o u n d i n t e r e s t * /3 # i n c l u d e < s t d i o . h >4 # i n c l u d e < ma t h . h >5
6 / * f u n c t i o n ma i n b e g i n s p r o g r a m e x e c u t i o n * /7 i n t ma i n ( )8 {9 d o u b l e a mo u n t ; / * a mo u n t o n d e p o s i t * /10 d o u b l e p r i n c i p a l = 1 0 0 0 . 0 ; / * s t a r t i n g p r i n c i p a l * /11 d o u b l e r a t e = . 0 5 ; / * i n t e r e s t r a t e * /12 i n t y e a r ; / * y e a r c o u n t e r * /13
14 / * o u t p u t t a b l e c o l u mn h e a d * /15 p r i n t f ( " %4 s %2 1 s \ n " , " Y e a r " , " A mo u n t o n d e p o s i t " ) ;16
17 / * c a l c u l a t e a mo u n t o n d e p o s i t f o r e a c h o f t e n y e a r s * /18 f o r ( y e a r = 1 ; y e a r < = 1 0 ; y e a r + + ) {19
20 / * c a l c u l a t e n e w a mo u n t f o r s p e c i f i e d y e a r * /21 a mo u n t = p r i n c i p a l * p o w( 1 . 0 + r a t e , y e a r ) ;22
23 / * o u t p u t o n e t a b l e r o w * /24 p r i n t f ( " %4 d %2 1 . 2 f \ n " , y e a r , a mo u n t ) ;25 } / * e n d f o r * /26
33
27 r e t u r n 0 ; / * i n d i c a t e p r o g r a m e nd e d s u c c e s s f u l l y * /
8/2/2019 Comp 132 Notes 3 Program Control
33/50
OutlineOutline
Copyright 19922004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
fig04_06.c (Part 2 of2)
Program Output
Y e a r A mo u n t o n d e p o s i t1 1 0 5 0 . 0 02 1 1 0 2 . 5 03 1 1 5 7 . 6 34 1 2 1 5 . 5 15 1 2 7 6 . 2 86 1 3 4 0 . 1 07 1 4 0 7 . 1 08 1 4 7 7 . 4 69 1 5 5 1 . 3 31 0 1 6 2 8 . 8 9
28
29 } / * e n d f u n c t i o n ma i n * /
34
8/2/2019 Comp 132 Notes 3 Program Control
34/50
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 productRunning product
35
8/2/2019 Comp 132 Notes 3 Program Control
35/50
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 issupplied 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
8/2/2019 Comp 132 Notes 3 Program Control
36/50
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 sentinelvalue.
A sentinel must be a value that could not occur as data.
37
8/2/2019 Comp 132 Notes 3 Program Control
37/50
Sentinel-controlled Loops
Example:
/* computes the sum of a list of exam scores */
#include
#define SENTINEL 99
intmain(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) {
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;
}
Running sumRunning sum
38
8/2/2019 Comp 132 Notes 3 Program Control
38/50
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
8/2/2019 Comp 132 Notes 3 Program Control
39/50
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
8/2/2019 Comp 132 Notes 3 Program Control
40/50
Example With the for Statement
sum = 0;
for (i=0; i
8/2/2019 Comp 132 Notes 3 Program Control
41/50
Example With the for Statement
Suppose that we also want to compute the inner sums.
sum = 0;
for(i=0; i
8/2/2019 Comp 132 Notes 3 Program Control
42/50
Example With the while Statement
Likewise the for and while loops
can be nested one inside the other.
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);
}
43
do while Statement
8/2/2019 Comp 132 Notes 3 Program Control
43/50
do-while Statement
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 atthe end of the loop body.
Such a loop can be created by the do-while statement:
do {
statament1;statement2;
.
.
} while (condition);
Note that there isa semi-colon here.
Note that there isa semi-colon here.
Syntax:
44
8/2/2019 Comp 132 Notes 3 Program Control
44/50
do-while Statement
With the do-while statement, first the loop is executed andthen the condition is tested. If the condition is true, the loopbody is repeated.
Therefore, a do-while loop is always executed at least once.
Example: Entering a valid letter from the prompt:
Since the user must enter at least one data character, the do-while is an ideal statement to implement this loop.
do {
printf(Enter a letter from A through Z>);
scanf(%c, &letter_choice);
} while (letter_choiceZ);
45
8/2/2019 Comp 132 Notes 3 Program Control
45/50
Alternative With the while Statement
printf(Enter a letter from A through Z>);scanf(%c, &letter_choice);
while (letter_choiceZ) {
printf(Enter a letter from A through Z>);
scanf(%c, &letter_choice);
}
Which one is better?
Why?
Which one is better?
Why?
46
C L E
8/2/2019 Comp 132 Notes 3 Program Control
46/50
Common Loop Errors
The following code should sum up the values from 0 to n.
The following code should ask for numbers and calculate a
running sum until a sentinel value (-99) is encountered.
for (i=0, i
8/2/2019 Comp 132 Notes 3 Program Control
47/50
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 innermostenclosing loop to be exited immediately.
48
d St t t
8/2/2019 Comp 132 Notes 3 Program Control
48/50
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 anddo loops, this means that the condition part is
executed immediately
in the for loop, control passes to loop variableupdate step.
49
Example for continue
8/2/2019 Comp 132 Notes 3 Program Control
49/50
Example for continue
#include
int main(void){
int sum=0, n=1;while (n
8/2/2019 Comp 132 Notes 3 Program Control
50/50
Reading
Sections 3.1-3.10 and
Chapter-4 of the textbook
Recommended