Flow control with break
and continue
From cppreference.com
Sometimes it is necessary to exit a loop before the loop condition is met. This is easily done with the break
keyword:
for ( /* loop range */ ) { ... if ( /* condition */ ) { break; } ... }
The loop is then left immediately, processing continues after the end of the for
loop.
Another method of flow control allows to directly start the next iteration of a loop:
for ( /* loop range */ ) { ... if ( /* condition */ ) { continue; } ... }
In this case, the loop condition is checked and, if the condition still holds true, the next loop iteration takes place.
See the following example of a very simple prime number generator:
Run this code
Output:
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime