Chapter 06
Chapter 06
printf
Done 5
No
times?
Y es
Types of Loops
• Pretest - a logical condition is checked
before each repetition to determine if the
loop should terminate
– while loop
– for loop
• Posttest - a logical condition is checked
after each repetition for termination
– do-while loop
PreTest vs. PostTest Loops
Pretest Loop Posttest Loop
A ction or
Condition
A ctions
true
true
false
A ction or
Condition
A ctions
false
Terminating Loops
• Counter-controlled loops - a loop controlled
by a counter variable, generally where the
number of times the loop will execute is
known ahead of time
• Event-controlled loops - loops where
termination depends on an event rather than
executing a fixed number of times
Counter-Controlled Loops
• Generally with for loops
• Can generally infer number of repetitions
from code
• Examples:
– read 5 numbers
– print 7 items
– sort n items
Event-Controlled Loops
• Generally with while, do-while loops
• Can’t infer number of repetitions from
program
• Examples:
– read until input ends
– read until a number encountered
– search through data until item found
Parts of Loop
• Initialization - commands to set up loop (set
counter to initial value, etc.)
• Terminating condition - logical condition
that is checked to terminate loop
• Body of loop - commands repeated
– action(s) - statements to repeat
– update(s) - statements to update values
associated with loop (counters, etc.)
Parts of Loop Example
Init: set counter to 0 counter = 0;
Termination: counter < 5
Body:
(counter < 5)
Action: print *
Update: add 1 to true
counter false
printf("*\n");
counter++;
Importance of Update
What if command counter = 0;
counter++;
left out?
(counter < 5)
never met.
Infinite Loops
• Loop starts but termination condition never
met:
– you forget to increase counter
– user never enters terminating data item
– etc.
• Results
– program may stop (doing nothing repeatedly)
– computer may repeatedly print some data out
Termination Conditions in C
• Loops in C always continue when the
termination condition is true and end when
the condition is false
• Conditions can be rephrased if needed
(positive termination conditions can be
negated)
• Condition only checked at fixed points
(does not have to hold true during body)
Pretest Loop: While
Syntax:
while (condition)
statement; Condition
Corresponds to:
true
if (!condition) DONE false
statement
Statement
if (!condition) DONE
statement
...
Example of While
int counter = 0;
counter = 0;
counter++;
} true
false
printf("*\n");
counter++;
single statement is
compound
Executing More Than One Stmt
• In C, loops repeat one statement
• Generally we always use a compound
statement as that statement:
while (condition) {
/* body */
}
• Useful even when body has one or no
statements
Empty Statements and Loops
• What’s wrong with this?
counter = 0;
while (counter < 5);
{
printf(“*\n”);
counter++;
}
• Note the ; after the condition in the while,
its an empty statement (which is the body of
the while), so the while is an infinite loop
Event-Controlled While
• While loops are often used to test for the
occurrence of events that terminate loops
• Example:
– read in a set of numbers until a particular value
is encountered
– along the way count the set of numbers and the
total of the numbers
– print out the average of the numbers
– does not terminate after a fixed point
Calculate Average Loop
total = 0;
counter = 0;
GetFirstNumb er
number != 999
true
false
total += number;
counter++;
GetNextNumb er
print average
Calculate Average Code
total = 0;
count = 0;
printf(“Please enter first number: “);
scanf(“%d”,&number);
while (number != -999) {
total += number;
count++;
printf(“Please enter next number: “);
scanf(“%d”,&number);
}
printf(“Average is %.3f\n”,(float) total
/ count);
Using a Sentinel
• The value -999 is sometimes referred to as a
sentinel value
• The value serves as the “guardian” for the
termination of the loop
• Often a good idea to make the sentinel a
constant:
#define STOPNUMBER -999
while (number != STOPNUMBER) ...
Compound Conditions
• Often the termination condition is compound:
ans = ‘N’;
while (!((ans == ‘Y’) || (ans == ‘y’))) {
printf(“Enter id# and salary: “);
scanf(“%d %f”,&id,&salary);
printf(“You entered id#%1d and salary
$%.2f, Is this correct? (Y/N)
“,id,salary);
scanf(“ %c”,&ans);
}
Making Sure Loop is Entered
• Note in previous loop, we had to set
variable ans to an initial value, ‘N’
• This is because a while loop tests its
condition before entering the loop, and if
the condition is already false, the loop never
executes
• Sometimes it is useful to have a loop that
always executes at least once
Posttest Loop: Do-While
Syntax:
do {
statement(s) statement(s)
Corresponds to:
statement
condition
if (!condition) DONE
statement false
if (!condition) DONE
...
Using the Do-While
do {
printf(“Enter id# and salary: “);
scanf(“%d %f”,&id,&salary);
printf(“You entered id#%1d and salary
$%.2f, Is this correct? (Y/N) “
,id,salary);
scanf(“ %c”,&ans);
} while (!((ans == ‘Y’) || (ans == ‘y’)));
printf(“Select
ReadOption
option:“); true
for ( init ;
condition ; Condition
update )
statement; true
counter variables
For Example
• Printing vertical line counter = 0;
of stars:
for (counter = 0;
counter < 5
counter < 5;
counter++)
true
printf(“*\n”);
printf("*\n"); false
counter++;
For Example - Sum of 1 to N
printf(“Number to sum to: “);
scanf(“%d”,&N);
total = 0;
for (I = 1; I <= N; I++)
total += I;
/* total is now 1 + 2 + … + N */
For Example - Max of N Scores
printf(“Number of students: “);
scanf(“%d”,&NumStudents);
for (I = 0; I < NumStudents; I++) {
printf(“Enter student score %d: “);
scanf(“%d”,&score);
if (score > max)
max = score;
}
/* max is highest score entered */
The Comma Form
• Possible to evaluate more than one
expression (assignment) in initialization or
update by separating each by commas
• Syntax: expression , expression , …
printf(“Number to sum to: “);
scanf(“%d”,&N);
for (total = 0, I = 1;
I <= N;
total += I, I++);
/* total is now 1 + 2 + … + N */
Directions of Counting
for (I = 10; I >= 1; I--)
printf(“%d…\n”,I);
printf(“0 BLASTOFF!\n”);