break in C

The break statement exits or terminates the loop or switch statement based on a certain condition, without executing the remaining code.

Syntax of break in C

break;

Flowchart of break Statement

 

Uses of break in C

The break statement is used in C for the following purposes:

  1. To come out of the loop.
  2. To come out from the nested loops.
  3. To come out of the switch case.

Note: If the break statement is used inside an inner loop in a nested loop, it will break the inner loop without affecting the execution of the outer loop.

Example of break Statement

The statements inside the loop are executed sequentially. When the break statement is encountered within the loop and the condition for the break statement becomes true, the program flow breaks out of the loop, regardless of any remaining iterations.

C




// C program to illustrate the break in c loop
#include <stdio.h>
int main()
{
    int i;
    // for loop
    for (i = 1; i <= 10; i++) {
  
        // when i = 6, the loop should end
        if (i == 6) {
            break;
        }
        printf("%d ", i);
    }
    printf("Loop exited.\n");
    return 0;
}


Output

1 2 3 4 5 Loop exited.

Explanation:

  • Loop Execution Starts and goes normally till i = 5.
  • When i = 6, the condition for the break statement becomes true and the program control immediately exits the loop.
  • The control continues with the remaining statements outside the loop.

Note: The break statement only break a single loop per usage. If we want to exit multiple loops in nested loops, we have to use multiple break statements for each of the loop.

The break statement is also used inside the switch statement to terminate the switch statement after the matching case is executed.

Jump Statements in C

In C, jump statements are used to jump from one part of the code to another altering the normal flow of the program. They are used to transfer the program control to somewhere else in the program.

In this article, we will discuss the jump statements in C and how to use them.

Similar Reads

Types of Jump Statements in C

There are 4 types of jump statements in C:...

1. break in C

The break statement exits or terminates the loop or switch statement based on a certain condition, without executing the remaining code....

2. Continue in C

...

3. Goto Statement in C

The continue statement in C is used to skip the remaining code after the continue statement within a loop and jump to the next iteration of the loop. When the continue statement is encountered, the loop control immediately jumps to the next iteration, by skipping the lines of code written after it within the loop body....

4. Return Statement in C

...