Continue Statement with do-while Loop
In do-while loop, the condition is checked after executing the loop body. When a continue statement is encountered in the do-while loop, the control jumps directly to the condition checking for the next loop, and the remaining code in the loop body is skipped.
Example:
C++
// C program to explain the use // of continue statement with while loop #include <iostream> using namespace std; int main() { int i = 0; // loop from 1 to 10 do { // If i is equals to 4, // continue to next iteration // without printing i++; if (i == 4) { continue ; } else { // otherwise print the value of i cout << i << ' ' ; } } while (i < 10); return 0; } |
1 2 3 5 6 7 8 9 10
Here, 4 is not printed as a continue statement is encountered in the case of i = 4.
Note: In while and do-while loop, we updated the loop variable i before the continue statement or else we will keep encountering continue before updating the loop variable creating an infinite loop.
continue Statement in C++
C++ continue statement is a loop control statement that forces the program control to execute the next iteration of the loop. As a result, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
continue;
Example: Consider the situation when you need to write a program that prints numbers from 1 to 10 but not 4. It is specified that you have to do this using loop and only one loop is allowed to use. Here comes the usage of the continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the iterator with 4. If it is equal to 4 we will use the continue statement to continue to the next iteration without printing anything otherwise we will print the value.