Continue Statement
Now we'll look at the continue
statement, which allows us to skip the rest of the current loop iteration and proceed to the next iteration. Imagine you go running every day, but some days have bad weather and you don't want to run. The continue
statement allows you to skip such days and continue with the next days.
For example, we want to print all numbers between 1 and 10 except numbers that are multiples of 3:
int number = 1;
while (number <= 10) {
if (number % 3 == 0) { // If number is a multiple of 3
number++;
continue; // Skip this iteration
}
std::cout << number << std::endl;
number++;
}
// Prints one below the other: 1 2 4 5 7 8 10
In this example, we go through numbers from 1 to 10. If number
is a multiple of 3, we increment it by 1 and skip its printing using the continue
statement and proceed to the next loop iteration. When number
is not a multiple of 3, we print it and increment it by 1.
It's important to realize that as soon as the program encounters a continue
statement, it skips the rest of the statements in the loop's code block and continues with the next iteration. Let's go through a few iterations to make everything clear:
- The loop starts, and the value of
number
is 1. - The condition is skipped since
number
is not a multiple of 3. number
is printed (value 1)number
is incremented by 1- We return to the beginning of the loop. Now number has value 2.
- The condition is skipped since
number
is not a multiple of 3. number
is printed (value 2)number
is incremented by 1- We return to the beginning of the loop. Now number has value 3.
- The condition applies, so
number
is incremented by 1 - The rest of the iteration is skipped
- We return to the beginning of the loop. Now number has value 4.
- …
Instructions
Using a while
loop, go through count
from 1 to 10 and print count
when it's not a multiple of 2. Use the continue
statement to skip numbers that are multiples of 2. Don't forget to increment the variable count
by 1.
Start programming for free
6/9