The continue keyword

We saw in a previous post how to get out of a loop thanks to the break keyword. But let’s now imagine that you just want to skip the current iteration under some condition and continue with the next one. continue ? You know where I’m going ? So let’s take the same example in which we have a loop with a counter from 0 to 9 and displays the counter value in each iteration. The “special” condition to break the normal sequence occurs when the counter is equal to 5 (Figure 1).

continue

Figure 1

With break, the displayed values were 0, 1, 2, 3 et 4. Then the loop just stopped and the execution continued with the first line that follows it. But when we replace it with a continue, we can see that the result is different (Figure 2).

continue-result

Figure 2

We figure out that the value “5” is not displayed but all other values are. Indeed when the condition is met, the code that follows the continue inside the loop is skipped but the execution continues with the next iteration instead of leaving the loop.

Advertisements