C++ continue Statement

The continue statement in C++ is used to skip some statements inside the body of the loop and forces the next iteration of the loop. The continue statement skips the rest of the statements of loop body in the current iteration.
Most of the time, continue statement is used with conditional statement inside body of the loop. Use of continue statement, change the normal sequence of execution of statements inside loop.

  • Inside while and do..while loop, continue statement will take control to the condition statement.
  • Inside for loop, continue statement will take control to the update statement(increment/decrement of loop control variable) then condition will be checked.

Syntax of continue Statement

continue;

Flow Diagram of continue Statement

C++ Continue Statement Control Flow Diagram
Uses of continue Statement
  • We can use continue statement inside any loop(for, while and do-while). It skips the remaining statements of loop's body and starts next iteration.
  • If we are using continue statement inside nested loop, then it will only skip statements of inner loop from where continue is executed.

C++ continue Statement Example Program

/* 
 * C++ program to find sum of even numbers
 */
#include <iostream>
using namespace std;

int main(){

    int N, counter, sum=0;
    cout << "Enter a positive number\n";
    cin >> N;
     
    for(counter=1; counter <= N; counter++){
     //Using continue statement to skip all odd numbers
        if(counter%2 == 1){
            continue;
        }
        sum+= counter;
    }
    cout <<"Sum of all even numbers from 1 to " <<N<<" = "<< sum;
     
    return 0;
}
Output
Enter a positive number
6
Sum of all even numbers from 1 to 6 = 12
In above program, we first take an integer N as input from user. We want to find the sum of all even numbers between 1 to N. If counter is odd number then continue statement will force next iteration without executing sum statement. Here, continue statement is used to skip all odd numbers while finding even numbers sum.