C

In C Programming, A Break Statement Is Used

Inside loops and switch cases, the break statement is used.

Break statement (C)

1. It is used to exit the loop immediately. When a break statement is encountered within a loop, control exits the loop and the loop is terminated. When used inside a loop, it is combined with an if statement.
2. This is also applicable in switch case control structures. When it is encountered in a switch-case block, control exits the switch-case (see the example below).

Break statement flow diagram

Syntax:

break;

Use of break in a while loop as an example

#include <stdio.h>
int main()
{
     int num =0;
     while(num<=100)
     {
        printf("value of variable num is: %d\n", num);
        if (num==2)
        {
            break;
        }
        num++;
     }
     printf("Out of while-loop");
     return 0;
}

Output:

value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
Out of while-loop

Use of break in a for loop as an example

#include <stdio.h>
int main()
{
      int var;
      for (var =100; var>=10; var --)
      {
           printf("var: %d\n", var);
           if (var==99)
           {
               break;
           }
      }
     printf("Out of for-loop");
     return 0;
}

Output:

var: 100
var: 99
Out of for-loop

Use of a break statement in a switch-case example

In a switch case block, you should always use a break statement; otherwise, once a case block is executed, the rest of the subsequent case blocks will be executed. For example, if we don’t use the break statement after each case block, the program’s output would be:

#include <stdio.h>
int main()
{
      int num;
      printf("Enter value of num:");
      scanf("%d",&num);
      switch (num)
      {
          case 1:
             printf("You have entered value 1\n");
             break;
          case 2:
             printf("You have entered value 2\n");
             break;
          case 3:
             printf("You have entered value 3\n");
             break;
          default:
             printf("Input value is other than 1,2 & 3 ");
     }
     return 0;
}

Output:

Enter value of num:2
You have entered value 2

In a switch case block, you should always use a break statement; otherwise, once a case block is executed, the rest of the subsequent case blocks will be executed. For example, if we don’t use the break statement after each case block, the program’s output would be:

Enter value of num:2
You have entered value 2
You have entered value 3
Input value is other than 1,2 & 3

Related Articles

Leave a Reply

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

Back to top button