C Programming Tutorial - ITDeveloper

ITDeveloper : C Programming

C Programming

Step by Step Tutorials


Share with a Friend

break statement in C

The break statement ends the loop immediately when it is encountered. Its syntax is:

break;

The break statement is almost always used with if...else statement inside the loop. It is also used in switch case.

 Working of break statement in C

Example 1: break statement

// Program to calculate the sum of numbers (10 numbers max)

// If the user enters a negative number, the loop terminates

#include <stdio.h>

int main() {

   int i;

   int num, sum = 0.0;

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

      printf("Enter Number %d : ", i);

      scanf("%d", &num);

      // if the user enters a negative number, break the loop

      if (num < 0) {

         break;

      }

      sum += num; // sum = sum + number;

   }

   printf("Sum = %d", sum);

   return 0;

}

OUTPUT:

Enter Number 1 : 1

Enter Number 2 : 2

Enter Number 3 : 3

Enter Number 4 : 4

Enter Number 5 : 5

Enter Number 6 : -1

Sum = 15

This program calculates the sum of a maximum of 10 numbers. If the user enters a negative number, the break statement is executed. This will end the for loop, and the sum is displayed.

Example 2:

#include<stdio.h>

#include<stdlib.h>

void main ()

 {

   int i;

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

     {

       printf("%d \n",i);

       if(i == 5)

         break;

     }

  printf("Out of loop when i = %d",i);

}

OUTPUT:

0

1

2

3

4

5

Out of loop when i = 5

Example 3:

break statement inside the switch case

#include <stdio.h>

void main()

{

char opt;

printf("Enter the option "A", "B", "C" or "D" : ");

scanf( "%c", &opt );

switch (opt)

{

case 'A':

printf( "You have entered option A " );

break;

case 'B':

printf( "You have entered option B " );

break;

case 'C':

printf( "You have entered option C " );

break;

case 'D':

printf( "You have entered option D ");

break;

default:

printf ( "It is Wrong input. You have not entered option A, B, C, or D ");

}

}

OUTPUT 1:

Enter the option "A", “B”, “C” or “D” :A
You have entered option A

OUTPUT 2:

Enter the option "A", “B”, “C” or “D” :E
It is Wrong input. You have not entered option A, B, C, or D