Break Statement in C Language


The break statement in C is used to exit from a loop or switch statement prematurely. It provides a way to terminate the current iteration of a loop or switch case when a certain condition is met, improving control flow in programs.

1. Using Break in Loops

When used inside a loop, the break statement immediately terminates the loop and transfers control to the statement following the loop.

In this example, the loop iterates from 0 to 9, but when i equals 5, the break statement is executed, terminating the loop early. The output will be:

2. Using Break in Switch Statements

The break statement is also commonly used in switch statements to exit from a case once it has been executed. Without a break, the program continues to execute the subsequent cases (a behavior known as "fall through").

In this example, since choice is 2, it will print "Choice 2 selected" and then exit the switch statement due to the break.

3. Using Break in Nested Loops

When using break in nested loops, it will only terminate the innermost loop. If you need to break out of outer loops, you can use labeled statements.

In this example, the inner loop will terminate when j equals 1, causing the output:


    i = 0, j = 0
    i = 1, j = 0
    i = 2, j = 0
        

Conclusion

The break statement is a powerful tool in C programming that allows for greater control over loop and switch execution. By using break, programmers can enhance the efficiency and readability of their code by preventing unnecessary iterations or executions.






Advertisement