In a c program, if there is a situation where we want to come out of the loop without completing the loop, then we can use break statement.

To execute the break-statement, we use if-statement.

Let us take an example,

Quiz=comparison of two number and find the match.
#include<stdio.h>

int main()
{
 int num,i;
printf("Enter the number\n");
scanf("%d",&num);

for(i=1;i<=100;i++)
{
 if(i==num)
{
 printf(" match found=%d",i):
 break;
}
i++;
}
return 0;
}
Output:: 
 Enter the number
 44
 match found=44 


In the above example, we have declared a "num" variable, and took the runtime input to the "num" variable. Inside the for-loop, we have compared the "num" value with the ith value of the for-loop iteration from 1 to 100, if the "num" value matches with the  "ith" value then the control will come out of the for-loop without iterating the further numbers till 100 and print the matched number.

The comparison is done only till the condition under the if-statement matches. After getting the match, the break statement does its work and comes out of the loop without checking the further iterations.

 

Advantages of break statement:


  •     Increases the complexity of the program
  •     No need to check the entire for-loop.
  •     The break-statement can be used in a while loop, for loop, do-while loop, and switch-statement.
  •     It can be used in a switch-statement to terminate the switch statement.

 

To know about the switch-statement please follow the below link.

conditional statements in c




See Also:

 while loop
 for loop