C++ break Statement

Break statement

A break statement is a jump statement that terminates the execution of a loop and the control is transferred to resume normal execution after the body of the loop. 

Flow chart:-

Contents:-

  1. Break statement in for loop
  2. Break statement in while loop
  3. Break statement in nested loop

Break statement in for loop

Code:

C++ Code

#include<iostream>

using namespace std;

void break_statement() {
  for (int i = 1; i <= 10; ++i) {
    if (i == 5) {
      break;
    }
    cout << i << " ";
  }
}
int main() {
  break_statement();
  return 0;
}

Output: 1 2 3 4

Explanation:- In the above code, the for loop will iterate 10 times, but as soon as the value of i reaches 5, the for loop is terminated, because of the break statement.

Break statement in while loop

Code:

C++ Code

#include<iostream>
using namespace std;

void break_statement() {
  int i = 10;
  while (i >= 1) {
    if (i == 6) {
      break;
    }
    cout << i << " ";
    --i;
  }
}
int main() {
  break_statement();
  return 0;
}

Output: 10 9 8 7

Explanation:- In the above code, the while loop will iterate 10 times, but as soon as the value of i reaches 6, the while loop is terminated, because of the break statement.

Break statement in nested loop

Code:

C++ Code

#include<iostream>
using namespace std;

void break_statement() {
  cout << "The value of i and j are:" << '\n';
  for (int i = 0; i <= 5; ++i) {
    for (int j = 0; j <= 5; ++j) {
      if (i + j >= 3) break;
      cout << "i = " << i << ", " << "j = " << j << '\n';
    }
  }
}
int main() {
  break_statement();
  return 0;
}

Output:

Output:-

The value of i and j are:

i = 0, j = 0

i = 0, j = 1

i = 0, j = 2

i = 1, j = 0

i = 1, j = 1

i = 2, j = 0

Explanation:-

In the above code, when the sum of i + j value greater than or equal to 3 means the inner loop will terminate But the iteration of the outer loop is unaffected.

Note:- If a break statement is presented in a nested loop it will terminate only the inner loop in which the break statement is presented.

Special thanks to JAIGANESH R S for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article