Previous

C++ Break and Continue

Next

*The break Break statement*

The break statement is used in a switch statement and in loop.The break statement transfers the control to the first statement following the switch or the loop.A break is usually associated with an if statement .When it is encounred in loop,the control is immediately transferred to the first statement after the loop,without waiting to get back to conditional test.

Definition of break :-

A statement that causes the transfer of control outside a loop or a switch statement.

Example:-

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 10; i++) {
    if (i == 4) {
      break;
    }
    cout << i << "\n";
  } 
  return 0;
}

OUTPUT:-

0
1
2
3

 

Explain this code:-  In this code segment , the moment the condition  (i == 4) is equal to 4,the  control is transferred out of the for loop.Note that if the break statement is encountered in nested loop,then the control is transferred outside the loop in which it is places.

*The continue Statement *

Unlike the break statement ,the continue statement takes the control to the beginning of the loop and skip the rest of the loop body.The continue statement is only used in loop,not in a switch statement .

Definition ofcontinue statement:-

A statement that causes the transfer of control beginning of a loop.The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

Example :-

#include <iostream>
using namespace std;

int main() {
  for (int i = 0; i < 10; i++) {
    if (i == 4) {
      continue;
    }
    cout << i << "\n";
  }   
  return 0;
}

OUTPUT:-

0
1
2
3
5
6
7
8
9

Explain this code:- In this code segment the moment the condition ( i ==4 ) is equal to 4, the control is transferred to the beginning of the  loop, the loop control  variable is updates and the loop body  getss executed if the test condition results in true.