Break Statement in C

By | February 20, 2023

Prerequisite – Control Statements in C
In C, the “break” statement is used to immediately exit a loop. Here are a couple of examples of using “break” in different loops:

Example-1: Print numbers from 1 to 10 using a “for” loop and “break”

#include <stdio.h>

int main() {
    int i;

    for (i = 1; i <= 10; i++) {
        printf("%d ", i);

        if (i == 5) {
            break;
        }
    }

    return 0;
}

Output:

1 2 3 4 5

In this example, the “for” loop is used to print the numbers from 1 to 10. Within the loop, the if statement is used to check if the value of i is equal to 5. If i is equal to 5, the “break” statement is executed, and the loop is exited immediately. As a result, only the numbers from 1 to 5 are printed to the console.

Example-2: Print the first 5 even numbers using a “while” loop and “break”

#include <stdio.h>

int main() {
    int i = 1;
    int count = 0;

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

        if (count == 5) {
            break;
        }

        i++;
    }

    return 0;
}

Output:

2 4 6 8 10

In this example, the “while” loop is used to print the first 5 even numbers. The loop runs as long as the value of i is less than or equal to 10. Within the loop, the if statement is used to check if i is even (i.e., if i divided by 2 has a remainder of 0). If i is even, the number is printed to the console and the variable count is incremented. If count reaches 5, the “break” statement is executed, and the loop is exited immediately.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.