The break Statement

We know that the loop condition is responsible for controlling the execution of a loop. If at some point in time, the condition becomes false, then the loop terminates. But, that’s not the only way to terminate the loop. In this tutorial, we will learn an alternative approach to exit from the loop whenever we want.


Understanding the break Statement

The break statement is a control statement that allows us to terminate a loop (while, for, do-while) and a switch case prematurely. When it is encountered, it shifts the control to the statement that immediately follows the terminated statement.


Purpose and Usage

The primary purpose of the break statement is to

  • Exit a loop before it has finished all the iterations.
  • Exit a switch case after its evaluation.

Examples

Following are some of the examples demonstrating the use of the break statement:

Example 1: Using break in a for loop

#include<stdio.h>

int main()
{
    for (int i = 1; i <= 10; i++) {
        if (i == 5)
            break;   // Exit the loop when i is 5
        printf("%d ", i);    
    }
    return 0;
}

Output:

1 2 3 4

The loop terminates when i is 5. Due to this reason, values till 4 are displayed.

Example 2: Using break in a while loop

#include<stdio.h>

int main()
{
    int i = 1;
    while (i <= 10) {
        if (i == 5)             
            break;   // Exit the loop when i is 5
        printf("%d ", i);    
        i++;
    }
    return 0;
}

Output:

1 2 3 4

Example 3: Using break in a do-while loop

#include<stdio.h>

int main()
{
    int i = 1;
    do {
        if (i == 5) // Exit the loop when i is 5
            break;
        printf("%d ", i);    
        i++;
    } while (i <= 10);
    return 0;
}

Output:

1 2 3 4

Example 4: Using break in a switch case

#include<stdio.h>

int main()
{
    char grade = 'B';
    switch (grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        case 'B':
            printf("Well done!\n");  
            break;
        case 'C':
            printf("Passed.\n"); 
            break; 
        default:
            printf("Invalid grade.\n");
            break;
    }
    return 0;
}

Output:

Well done!

Bonus Example: Using break to terminate an infinite while loop

#include<stdio.h>

int main()
{
    char input;
    
    while (1) { // infinite loop
        printf("Enter 'x' to exit: ");
        scanf(" %c", &input);  
        
        if (input == 'x') {
            printf("Loop terminated.\n");
            break;
        }    
    }
    return 0;
}

Output:

Enter 'x' to exit: e
Enter 'x' to exit: r
Enter 'x' to exit: t
Enter 'x' to exit: x
Loop terminated.

The while loop will continue to run until the user enters x.

Notice the whitespace character before %c. This is a common practice to avoid reading any left over whitespace character in the input buffer. It ensures only the next non-whitespace character will be read.


Use Case

Scenario:  We have a list of integers representing the measurements of something. Our goal is to detect the first negative number in the list which indicates an error in the measurements.

Purpose:  This use case demonstrates how a break statement can be used to detect an error in a sequence of data.

Program:

#include<stdio.h>

int main()
{
    int measurements[] = {10, 20, 30, 40, -1, 50};
    
    // Calculating the length of the list.
    int length = sizeof(measurements) / sizeof(measurements[0]);
    int i;
    
    for (i = 0; i < length; i++) {
        if (measurements[i] < 0) { // if a negative number is encountered.
            printf("Error detected at position %d with measurement %d\n", i, measurements[i]);
            break; // Exit the loop
        }    
    }
    
    /*
      if the loop is not terminated prematurely,
      then the for loop will terminate naturally
      when variable i becomes equal to the length 
      of the measurements list.
    */
    if (i == length) 
        printf("No errors detected in the measurements.");
    return 0;
}

Output:

Error detected at position 4 with measurement -1

We will learn in the arrays chapter how to create a list (or an array) like one created in the program and how to find its length. For now, just observe the usefulness of the break statement.


Level-Up Your Understanding

Question 1: What will be the output of the following code?

for (int i = 0; i < 5; i++) {
       if (i == 3) {
           break;
       }
       printf("%d ", i);
}

Solution:  the output will be 0 1 2 because as soon as variable i becomes 3, the break statement is encountered and the loop terminates. 

Question 2:  How can you find the sum of numbers entered by the user and exit the loop using break when the user enters a negative number? 

Solution:  the following program is capable to take numbers from the user and exits when the user enters a negative number:

#include<stdio.h>

int main()
{
    int n;
    while (1) {
        printf("Enter a number: ");
        scanf("%d", &n);
        
        if (n < 0) {
            printf("Loop terminated.");
            break;
        }
    }
    return 0;
}

Output:

Enter a number: 10
Enter a number: 20
Enter a number: 2
Enter a number: 3
Enter a number: 89
Enter a number: -1
Loop terminated.

Question 3:  Modify the following code to stop printing numbers when it reaches the number 4.

int i = 0;
while (i < 10) {
    printf("%d", i);
    i++;
}

Solution:

int i = 0;
while (i < 10) {
    if (i == 4)
        break;
    printf("%d", i);
    i++;
}

Question 4:  How can you use a break statement to exit the loop after printing the first 5 multiples of 3?

Solution

#include<stdio.h>

int main()
{
    for (int i = 1, count = 0; count < 5; i++) {
        if (i % 3 == 0) {// if i is multiple of 3
            printf("%d ", i);
            count++;
        }
        
        if (count == 5)
            break;
    }
    return 0;
}

Output: 

3 6 9 12 15

Question 5:  How would you use a break statement to write a program to find the greatest common divisor of two positive integers?

Solution:

#include <stdio.h>

int main()
{
    int a, b, gcd;
    
    printf("Enter the two numbers: ");
    scanf("%d%d", &a, &b);
    
    for (gcd = a<b ? a:b; gcd > 0; gcd--) {
        if (a % gcd == 0 && b % gcd == 0) {
            printf("GCD of %d and %d is %d", a, b, gcd);
            break;
        }
    }
    return 0;
}

Output:

Enter the two numbers: 10 25
GCD of 10 and 25 is 5

Explanation:

  • GCD means finding the largest number which completely divides the given two numbers. 
  • First, we are asking the user to enter the two numbers. 
  • Within the loop, we are initializing the variable gcd with the smallest of the values in a and b. This is because the largest number out of the two can never be their gcd. 
  • Within the loop, we are checking whether the value of gcd is completely dividing both a and b. If yes, then the appropriate message is displayed and the loop terminates. 
  • We then are decrementing the value of gcd if the condition inside the loop is not satisfied.

In this way, we are finding the greatest common divisor of the two numbers a and b.


Conclusion

The break statement provides greater control over the flow of the program to the programmer. It allows us to terminate a loop or a switch prematurely based on some condition. They are very useful especially when the termination is based on the user input. Using this powerful tool, you can write wonderful programs that could solve many real-world problems. 



Leave a comment

Leave a comment

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

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.