C++ Tutorial C++ Advanced C++ References

C++ - Continue Statement



The continue statement in C++ let the program skip a block of codes for current iteration in a loop. Whenever the condition is fulfilled, the continue statement brings the program to the start of the loop.

When the continue statement is used in a nested loop (loop inside loop), it will skip innermost loop's code block as the condition is fulfilled.

Continue statement with While loop

In the example below, continue statement is used to skip the while loop if the value of variable j becomes 4.

#include <iostream>
using namespace std;
 
int main (){
  int j = 0;
  while (j < 6){
    j++;
    if(j == 4){
      cout<<"this iteration is skipped.\n"; 
      continue;
    }
    cout<<j<<"\n"; 
  }
  return 0;
}

The output of the above code will be:

1
2
3
this iteration is skipped.
5
6

Continue statement with For loop

In the example below, continue statement is used to skip the for loop if the value of variable i becomes 4.

#include <iostream>
using namespace std;
 
int main (){
  for (int i = 1; i <= 6; i++){
    if(i == 4) {
      cout<<"this iteration is skipped.\n"; 
      continue;
    }
    cout<<i<<"\n"; 
  }
  return 0;
}

The output of the above code will be:

1
2
3
this iteration is skipped.
5
6

Continue statement with Nested loop

The Continue statement skip the inner loop's block of codes whenever condition is fulfilled. In below mentioned example, program skips the inner loop only when j = 100.

//Nested loop without continue statement
#include <iostream>
using namespace std;
 
int main (){
  cout<<"# Nested loop without continue statement\n"; 
  for (int i = 1; i <= 3; i++){
    for (int j = 10; j <= 1000; j = j * 10) {
      cout<<i*j<<"\n"; 
    }
  }
  return 0;
}

The output of the above code will be:

# Nested loop without continue statement
10
100
1000
20
200
2000
30
300
3000

//Nested loop with continue statement
#include <iostream>
using namespace std;
 
int main (){
  cout<<"# Nested loop with continue statement\n"; 
  for (int i = 1; i <= 3; i++){
    for (int j = 10; j <= 1000; j = j * 10){
      if(j == 100){
        continue;
      }
      cout<<i*j<<"\n"; 
    }
  }
  return 0;
}

The output of the above code will be:

# Nested loop with continue statement
10
1000
20
2000
30
3000