Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of the Break Statement in C
3.
Flowchart of break in C
4.
Example of the Break Statement in C
4.1.
C
5.
How Does the Break Statement Work in C?
6.
Use of break statements in different cases with their examples:
6.1.
Simple Loops 
6.1.1.
Example:
6.2.
C
6.3.
Nested Loops 
6.3.1.
Example:
6.4.
C
6.5.
Infinite Loops 
6.5.1.
Example:
6.6.
C
6.7.
Switch case
6.7.1.
Example:
6.8.
C
7.
Features of the Break Statement
8.
Frequently Asked Questions
8.1.
Can the break statement be used outside of loops or switch cases?
8.2.
Is it possible to exit multiple nested loops with a single break statement?
8.3.
How does the break statement differ from the continue statement in C?
9.
Conclusion
Last Updated: May 22, 2024
Easy

Break Statement in C

Author Rahul Singh
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The break statement is a fundamental control flow construct in the C programming language. It allows you to exit from a loop or switch statement prematurely, giving you greater control over the execution of your code. By using the break statement, you can avoid unnecessary iterations & save valuable processing time. 

Break Statement in C

In this article, we will look into the syntax & usage of the break statement in various contexts, including simple loops, nested loops, infinite loops, & switch statements with clear code examples to illustrate every section properly.

Syntax of the Break Statement in C

The break statement in C has a straightforward syntax, making it accessible even for those new to programming. It consists solely of the keyword break;. When this statement is executed within a loop, it causes the loop to terminate immediately, & the program flow resumes at the statement following the loop. Here is how you would typically see it used:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;  // Exits the loop when i is equal to 5
    }
    printf("%d\n", i);
}


In this example, the loop is designed to print numbers from 0 to 9. However, due to the break statement, the loop exits prematurely when i equals 5. As a result, the numbers printed are from 0 to 4. This demonstrates the break statement's role in controlling the flow of execution by halting loop operations under specific conditions.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Flowchart of break in C

To visualize how the break statement works in C, let's take a look at a flowchart:

Flowchart of break in C

In this flowchart, we have a loop that continues executing as long as a certain condition is met. If the condition is true, the loop continues to the next iteration. However, if the break statement is encountered inside the loop, the program immediately exits the loop & jumps to the statement after the loop.

The break statement essentially "breaks" out of the loop, regardless of the condition. It provides a way to prematurely exit the loop based on some criteria or condition.

Example of the Break Statement in C

To further understand the break statement, let's look at a practical example. Consider a scenario where you need to search through an array of integers to find a specific value & stop searching once the value is found.

Here’s a simple C program that demonstrates this:

  • C

C

#include <stdio.h>

int main() {

   int numbers[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};

   int target = 4;

   int found = 0;  // This will track whether the target is found

   for (int i = 0; i < 10; i++) {

       if (numbers[i] == target) {

           printf("Found %d at index %d.\n", target, i);

           found = 1;

           break;  // Stop the loop as soon as we find the target

       }

   }

   if (!found) {

       printf("%d not found in the array.\n", target);

   }


   return 0;

}

Output

Found 4 at index 6.


In this example, the program contains an array of integers. The loop iterates over the array, & each element is checked against the target value. When the target is found, the message is printed showing the target & its index in the array, & then the break statement is executed, which immediately stops the loop. If the loop completes without finding the target, a message is printed to indicate that the target was not found.

How Does the Break Statement Work in C?

The break statement in C programming serves a straightforward purpose: it interrupts the current loop's execution. When the break statement is executed, it terminates the loop immediately, regardless of whether the loop’s condition has been fulfilled. The control of the program then jumps to the statement immediately following the loop.

Here’s a simple breakdown of its operation within a typical loop:

  1. Start of Loop: The loop begins execution, either a for, while, or do-while loop.
     
  2. Condition Check: At each iteration, the loop evaluates whether the specified condition remains true.
     
  3. Execution of Statements: The statements within the loop are executed sequentially.
     
  4. Encounter Break: If a break statement is encountered during the execution of these statements:
  • The loop is immediately exited.
     
  • No further iterations are performed.
     
  • The program resumes execution from the point right after the loop.
     

5. Continue After Loop: Execution continues with the subsequent statements outside the loop.

This mechanism is especially useful in situations where continuing the loop is redundant or unnecessary after a certain condition is met. For instance, in searching operations (like finding an item in a list), there is no need to continue the search once the item is found, thus a break statement can efficiently conclude the loop.

Use of break statements in different cases with their examples:

Simple Loops 

In simple loops, such as for, while, or do-while loops, the break statement is used to exit the loop prematurely based on a certain condition. Here's the syntax of using break in a simple loop:

for (initialization; condition; update) {
    // loop body
    if (break_condition) {
        break;
    }
}

Example:

  • C

C

#include <stdio.h>

int main() {

   int i;

   for (i = 1; i <= 10; i++) {

       if (i == 5) {

           break;

       }

       printf("%d ", i);

   }

   printf("\nBroke out of the loop at i = %d\n", i);

   return 0;

}

In this example, the break statement is used within a for loop. The loop iterates from 1 to 10, but when i becomes 5, the break statement is executed, causing the loop to terminate prematurely. The output will be:

1 2 3 4
Broke out of the loop at i = 5


The break statement allows you to exit the loop based on a specific condition, saving unnecessary iterations.

Nested Loops 

In nested loops, where one loop is placed inside another, the break statement can be used to exit the innermost loop based on a certain condition. Here's the syntax of using break in nested loops:

for (initialization1; condition1; update1) {
    for (initialization2; condition2; update2) {
        // inner loop body
        if (break_condition) {
            break;
        }
    }
    // outer loop body
}

Example:

  • C

C

#include <stdio.h>

int main() {

   int i, j;

   for (i = 1; i <= 3; i++) {

       for (j = 1; j <= 3; j++) {

           if (i == 2 && j == 2) {

               break;

           }

           printf("(%d, %d) ", i, j);

       }

       printf("\n");

   }

   return 0;

}

In this example, we have two nested for loops. The outer loop iterates over the values of i from 1 to 3, while the inner loop iterates over the values of j from 1 to 3. Inside the inner loop, we have a condition that checks if i is equal to 2 and j is equal to 2. If this condition is true, the break statement is executed, causing the inner loop to terminate prematurely.

The output of this program will be:

(1, 1) (1, 2) (1, 3)
(2, 1)
(3, 1) (3, 2) (3, 3)



As you can see, when i is 2 and j is 2, the break statement is encountered, and the inner loop is exited. The program then continues with the next iteration of the outer loop.

The break statement in nested loops allows you to exit the innermost loop based on a specific condition while continuing with the outer loop.

Infinite Loops 

An infinite loop is a loop that runs indefinitely because the termination condition is never met. In such cases, the break statement can be used to exit the loop based on a certain condition. Here's the syntax of using break in an infinite loop:

while (1) {
    // loop body
    if (break_condition) {
        break;
    }
}

Example:

  • C

C

#include <stdio.h>

int main() {

   int count = 0;

   while (1) {

       printf("Count: %d\n", count);

       count++;

       if (count == 5) {

           break;

       }

   }

   printf("Broke out of the infinite loop.\n");

   return 0;

}

In this example, we have an infinite while loop that runs indefinitely because the condition (1) is always true. Inside the loop, we have a counter variable count that is incremented in each iteration. We also have an if statement that checks if count is equal to 5. If this condition is true, the break statement is executed, causing the loop to terminate.

The output of this program will be:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Broke out of the infinite loop.


As you can see, the loop continues to run until count reaches 5. At that point, the break statement is encountered, and the loop is terminated. The program then proceeds to the next statement after the loop.

The break statement in infinite loops provides a way to exit the loop based on a specific condition, preventing the program from running indefinitely.

Switch case

The break statement is commonly used in switch statements to exit the switch block once a matching case is found and executed. Here's the syntax of using break in a switch statement:

switch (expression) {
    case value1:
        // code to be executed
        break;
    case value2:
        // code to be executed
        break;
    ...
    default:
        // code to be executed if no case matches
        break;
}

Example:

  • C

C

#include <stdio.h>

int main() {

   int choice = 2;

   switch (choice) {

       case 1:

           printf("You selected option 1.\n");

           break;

       case 2:

           printf("You selected option 2.\n");

           break;

       case 3:

           printf("You selected option 3.\n");

           break;

       default:

           printf("Invalid choice.\n");

           break;

   }

   printf("Outside the switch statement.\n");

   return 0;

}

In this example, we have a switch statement that checks the value of the choice variable. Each case represents a different option. When a matching case is found, the corresponding code block is executed, and the break statement is used to exit the switch statement.

The output of this program will be:

You selected option 2.
Outside the switch statement


Since the value of choice is 2, the second case is executed, and the message "You selected option 2." is printed. The break statement ensures that the program exits the switch statement and continues with the next statement after the switch.

If the break statement is omitted, the program will continue executing the code in the subsequent cases until a break statement is encountered or the end of the switch statement is reached.

The break statement in switch statements allows you to control the flow of execution and exit the switch block once a matching case is found and processed.

Features of the Break Statement

  1. Immediate termination: The break statement immediately terminates the execution of the innermost enclosing loop or switch statement in which it appears. It transfers the control to the next statement following the loop or switch.
     
  2. Affects only the innermost loop or switch: The break statement only affects the innermost loop or switch statement in which it is used. If there are nested loops or switches, the break statement will only exit the innermost one.
     
  3. Conditional execution: The break statement is often used in conjunction with conditional statements (e.g., if statements) to exit a loop or switch based on a specific condition. This allows for controlled termination of the loop or switch when a certain condition is met.
     
  4. Skips remaining iterations: When a break statement is encountered inside a loop, it skips any remaining iterations of the loop and transfers the control to the next statement after the loop. This can be useful when you want to exit the loop prematurely based on a certain condition.
     
  5. Helps in optimizing code: By using the break statement appropriately, you can optimize your code by avoiding unnecessary iterations or computations. If a certain condition is met and you no longer need to continue the loop or switch, using break can save time and resources.
     
  6. Enhances readability: The break statement enhances the readability of your code by clearly indicating the point at which a loop or switch should be terminated. It makes the code more structured and easier to understand.
     
  7. Used in combination with other control flow statements: The break statement can be used in combination with other control flow statements, such as continue and return, to create more complex flow control patterns in your program.

Frequently Asked Questions

Can the break statement be used outside of loops or switch cases?

No, using the break statement outside of loops or switch cases will result in a compile-time error. It is specifically designed to provide control flow within these constructs only.

Is it possible to exit multiple nested loops with a single break statement?

A single break statement can only exit the nearest enclosing loop or switch case. To exit multiple nested loops, you would need to use additional logic, such as flags or goto statements, which are generally discouraged.

How does the break statement differ from the continue statement in C?

The break statement terminates the entire loop or switch case immediately, while the continue statement skips the remaining code in the current iteration and proceeds to the next iteration of the loop.

Conclusion

In this article, we have learned about the break statement in C, starting with its basic syntax and how it operates within loops and switch cases. We discussed various examples, including simple loops, nested loops, infinite loops, and switch cases, demonstrating how the break statement can effectively manage control flow by terminating loops or switch cases prematurely when certain conditions are met. At the end we talked about the features of the break statement, such as its ability to provide immediate termination and control flow management, is crucial for writing efficient and clear code in C programming.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass