• Home
  • 5.5 break in Loops

5.5 break in Loops

View Categories

5.5 break in Loops

< 1 min read

Table of Contents

The break statement can be used inside loops to terminate the nearest enclosing loop immediately. When break is executed, control is transferred to the first statement following the loop.

This allows a loop to terminate before its controlling condition becomes false, which is useful when a required condition is detected during iteration.

Source Code #

#include <iostream>

int main()
{
    for (int number = 1; number <= 10; ++number)
    {
        if (number == 6)
        {
            break;
        }

        std::cout << number << '\n';
    }

    std::cout << "Loop terminated.\n";

    return 0;
}

Output #

1
2
3
4
5
Loop terminated.

Explanation #

  • The for loop is configured to iterate from 1 through 10.
  • During each iteration, the if statement checks whether number is equal to 6.
  • When number becomes 6, the condition evaluates to true.
  • break immediately terminates the for loop.
  • The value 6 is therefore not printed because break executes before the std::cout statement.
  • Execution continues with the statement following the loop.
  • break terminates only the nearest enclosing loop.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *