Flow of control in a C program - unbounded loops
The for loops that we've just seen should be used when we know,
ahead of time,
how many times we need to loop
(i.e. 10 times, or over the range 'a'..'z').
Such loops are termed bounded loops and,
unless we've made an unseen coding error,
always terminate after a fixed number of iterations.
There are also many occasions when we don't know,
ahead of time,
how many iterations may be required.
Such occasions require unbounded loops.
C provides two types of unbounded loop:
The most common is the while loop,
where zero or more iterations are made through the loop:
|
Less common is the do....while loop,
where at least one iteration is made through the loop:
|
#define NLOOPS 20
int i = 1;
int n = 0;
.....
while(i <= NLOOPS) {
printf("iteration number %i\n", i);
.....
.....
i = some_calculation_setting_i;
n = n + 1;
}
printf("loop was traversed %i times\n", n);
|
|
#define NLOOPS 20
int i = 1;
int n = 0;
.....
do {
printf("iteration number %i\n", i);
.....
.....
i = some_calculation_setting_i;
n = n + 1;
} while(i <= NLOOPS);
printf("loop was traversed %i times\n", n);
|
|
Notice that in both cases
we still use a variable, i,
to control the number of iterations of each loop,
and that the changing value of the variable is used to determine if the
loop should "keep going".
However, the statements used to modify the control variable
may appear almost anywhere in the loops.
They provide flexibility,
but can also be confusing when loops become severals tens or hundreds of
lines long.
Notice also that while,
and do....while loops
cannot introduce new variables to control their iterations,
and so we have to use existing variables from an outer lexical scope.
CITS2002 Systems Programming, Lecture 2, p13, 24th July 2024.
|