You do not need the if..else.
A loop has a
condition that determines whether it is executed/repeated. For example:
1 2 3 4 5 6 7 8
|
constexpr size_t N = 10;
size_t counter = 0
while ( counter < N ) {
// something
++counter;
}
// this is "at the end of the program"
|
The
something above is repeated for N times (unless the something modifies the counter).
The
condition is
counter < N
One can use
std::cin
in a condition. It is true if the stream is ok.
Formatted stream input operator returns the stream.
Therefore,
std::cin >> foo
can be used in a condition. It has a
side-effect of storing a value into variable foo.
More than one conditional expression can be combined with logical AND and logical OR.
In condition
foo and bar and gaz
the foo is evaluated first.
If foo is false, the whole condition is false. Else the bar is evaluated.
If bar is false, the whole condition is false. Else the gaz is evaluated.
If gaz is false, the whole condition is false. The condition is true only if all three subconditions ( foo, bar, gaz) are true.
For example:
(counter < N) and (std::cout << "Give an integer, (0 for quit)\n") and (std::cin >> input) and (0 != input)
* ends loop if N inputs have already been taken (without asking for more input)
* also ends loop if output fails (unlikely)
* also ends loop, if user writes a character and
input
is
int
* also ends loop if that successful input value is 0
... but you can use the if..else:
1. Keyword statements
break;
and
continue;
can be used within a loop.
1 2 3 4 5
|
while ( cond1 ) {
if ( cond2 ) break;
if ( cond3 ) continue;
// statements
}
|
If that cond2 is true, then the execution of the loop ends.
If that cond3 is true, then the the rest of the body (the statements) are skipped and execution continues from line 1, testing cond1 again.
2.
1 2 3 4 5 6 7 8
|
while ( cond4 ) {
if ( cond5 ) {
// make cond4 false
}
else {
// statements
}
}
|
If that cond5 is true, then statements (line 6) are skipped.
Since line 3 modifies what will be evaluated in cond4, the loop ends at this iteration.