Website For Developers

Break and Continue in C++



Break statement in C++

break is a reserved keyword in c++.
• Break keyword in C++ used in control statements or in condition statements to stop the cycle.
• Through break statements we can skip the remaining iteration of the loop and jump out from the loop body.

Syntax

break;


Example of break in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

// This program will break when user enter negative value
  int i, number;
  for(i=1; i>0; i++) {
    cout<< "Enter Positive Number Only: ";
    cin>> number;
    if (number < 0) {
      cout<< "ALERT!! You Entered Negative Number";
      break;
    }
  }
  getch();
  return 0;
}

Output

Enter Positive Number Only: 2
Enter Positive Number Only: 89
Enter Positive Number Only: 0
Enter Positive Number Only: 754
Enter Positive Number Only: -6
ALERT!! You Entered Negative Number



Continue statement in C++

continue is a reserved keyword in c++.
• Continue keyword in C++ used in control statements to skip the current cycle or iteration.
• In for loop, continue keyword will result in process control immediately jumps to update statement.
• In while loop or do-while loop flow control immediately jumps to the loop condition.
• Whenever continue comes, the remaining statements of current iteration will not execute.

Syntax

continue;


Example of continue in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {

// This program will skip the 3rd and 7th value
  int i;
  for(i=1; i<=10; i++) {
    if (i == 3 || i == 7) {
      continue;
    }
    cout<< i<< endl;
  }
  getch();
  return 0;
}

Output

1
2
4
5
6
8
9
10