Continue Statement
C++ continue Statement
In C++, the continue statement is used to skip the rest of the code inside the loop for the current iteration and move on to the next iteration. When encountered, the continue statement causes the remaining statements in the loop body to be skipped, and the loop's control variable is updated for the next iteration.
Example using continue within a for loop to skip printing even numbers:
#include <iostream>
int main() {
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
std::cout << "Skipping even number: " << i << std::endl;
continue;
}
std::cout << i << " ";
}
return 0;
}
Output:
1 Skipping even number: 2
3 Skipping even number: 4
5 Skipping even number: 6
7 Skipping even number: 8
9 Skipping even number: 10
In this example, when the loop encounters an even number (i % 2 == 0), the continue statement is executed, and the loop skips the std::cout << i << " "; statement for that iteration.
Another example using continue within a while loop:
#include <iostream>
int main() {
int i = 0;
while (i < 5) {
++i;
if (i == 3) {
std::cout << "Skipping iteration at i = " << i << std::endl;
continue;
}
std::cout << i << " ";
}
return 0;
}
Output:
1 2 Skipping iteration at i = 3
4 5
In this example, the loop prints numbers from 1 to 5 but skips the iteration when i is 3.
The continue statement is useful when you want to skip specific iterations based on a condition without executing the remaining code for that iteration. It allows you to customize the flow of the loop to meet specific requirements.