C++ continue statement

The continue statement is a control structure in C++ that allows you to skip the current iteration of a loop and move directly to the next iteration. The continue statement can be used in conjunction with for, while, and do...while loops to skip a specific iteration when a specific condition is met. The basic syntax of the continue statement is as follows:

1continue;

The continue statement must be placed inside the loop and can be used to skip the current iteration of the loop when a specific condition is met.

Let's take a look at two examples of the continue statement in C++ and their output:

Example 1: Simple continue Statement

1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 1; i <= 5; i++) 7 { 8 if (i == 2) 9 { 10 continue; 11 } 12 cout << "Value of i: " << i << endl; 13 } 14 15 return 0; 16}

In the above example, the continue statement is used inside the for loop to skip the current iteration of the loop when the value of i is equal to 2. The for loop initializes the value of i to 1 and continues to execute as long as i is less than or equal to 5. The continue statement is executed when the value of i is equal to 2, which skips the current iteration of the loop and continues with the next iteration. The output will be:

1Value of i: 1 2Value of i: 3 3Value of i: 4 4Value of i: 5

Example 2: Nested continue Statement

1#include <iostream> 2using namespace std; 3 4int main() 5{ 6 for (int i = 1; i <= 3; i++) 7 { 8 for (int j = 1; j <= 2; j++) 9 { 10 if (i == 2 && j == 1) 11 { 12 continue; 13 } 14 cout << "Value of i: " << i << " and j: " << j << endl; 15 } 16 } 17 18 return 0; 19}

In the above example, the continue statement is used inside a nested for loop to skip the current iteration of the inner loop when the value of i is equal to 2 and the value of j is equal to 1. The outer for loop initializes the value of i to 1 and continues to execute as long as i is less than or equal to 3. The inner for loop initializes the value of j to 1 and continues to execute as long as j is less than or equal to 2. The continue statement is executed when the value of i is equal to 2 and the value of j is equal to 1, which skips the current iteration of the inner loop and continues with the next iteration of the inner loop. The output will be:

1Value of i: 1 and j: 1 2Value of i: 1 and j: 2 3Value of i: 2 and j: 2 4Value of i: 3 and j: 1 5Value of i: 3 and j: 2