Changing the regular flow of control within loops
There are many occasions when the default flow of control in loops
needs to be modified.
Sometimes we need to leave a loop early,
using the break statement,
possibly skipping some iterations and some statements:
|
Sometimes we need to start the next iteration of a loop,
even before executing all statements in the loop:
|
for(int i = 1 ; i <= 10 ; i = i+1) {
// Read an input character from the keyboard
.....
if(input_char == 'Q') { // Should we quit?
break;
}
.....
.....
}
// Come here after the 'break'. i is unavailable
|
|
for(char ch = 'a' ; ch <= 'z' ; ch = ch+1) {
if(ch == 'm') { // skip over the character 'm'
continue;
}
.....
.....
statements that will never see ch == 'm'
.....
.....
}
|
|
In the first example,
we iterate through the loop at most 10 times,
each time reading a line of input from the keyboard.
If the user indicates they wish to quit,
we break out of the bounded loop.
In the second example,
we wish to perform some work for all lowercase characters,
except 'm'.
We use continue to ignore the following statements,
and to start the next loop (with ch == 'n').
CITS2002 Systems Programming, Lecture 2, p15, 24th July 2024.
|