C++ continue statement
Created By: chatGPT
Continue statement in C++ is used within loops to skip the current iteration and jump to the next iteration of the loop. It is particularly useful when you want to bypass certain parts of the loop based on a condition. This can help you avoid additional nesting of code and improve readability. Below is a representation of how the continue statement works within a loop.
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " "; // Print odd numbers
}
In the above example, we loop through the numbers from 1 to 10. When the number is even, the continue statement is triggered, which causes the loop to skip the current iteration and move to the next number. As a result, only odd numbers are printed: 1, 3, 5, 7, 9.
Output:
1 3 5 7 9
You can also use the continue statement within nested loops, where it will only affect the innermost loop that contains it. Below is an example showing how it can be applied in nested loops.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue; // Skip the second column
}
std::cout << "(" << i << ", " << j << ") ";
}
}
In this case, when
j
equals 2, the continue statement skips to the next iteration in the inner loop, effectively skipping the printing of the second column for each row. The output will look like this:Output:
(1, 1) (1, 3) (2, 1) (2, 3) (3, 1) (3, 3)