Continue Statement with Nested Loops

Using continue, you skip the current iteration of the inner loop when using nested loops. 

Example:

C++




// C++ program to explain the use
// of continue statement with nested loops
  
#include <iostream>
using namespace std;
  
int main()
{
  
    for (int i = 1; i <= 2; i++) {
        for (int j = 0; j <= 4; j++) {
            if (j == 2) {
                continue;
            }
            cout << j << " ";
        }
        cout << endl;
    }
  
    return 0;
}


Output

0 1 3 4 
0 1 3 4 

Continue skips the current iteration of the inner loop when it executes in the above program. As a result, the program is controlled by the inner loop update expression. In this way, 2 is never displayed in the output.

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;

Flowchart of continue Statement in C++

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. 

Similar Reads

Continue Statement with for Loop

If continue is used in a for loop, the control flow jumps to the test expression after skipping the current iteration....

Continue Statement with While Loop

...

Continue Statement with do-while Loop

With continue, the current iteration of the loop is skipped, and control flow resumes in the next iteration of while loop....

Continue Statement with Nested Loops

...

Continue Statement vs Break Statement

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....