Sometimes, it is required to jump out of a loop irrespective of the conditional test value. Break statement is used inside any loop to allow the control jump to the immediate statement following the loop.
The syntax of Break Statement
When nested loops are used, then break jumps the control from the loop where it has been used. Break statement can be used inside any loop i.e., while, do-while, for and also in
Break statement can be used inside any loop i.e., while, do-while, for and also in a switch statement.
C Program to illustrate break statement
Write a program to calculate the first smallest divisor of a number.
/*Program to calculate smallest divisor of a number */
printf(“Enter any number:\n”);
if ((num % i) == 0)
printf(“Smallest divisor for number %d is %d”,num,i);
Enter any number:
Smallest divisor for number 9 is 3
In the above program, we divide the input number with the integer starting from 2 onwards, and print the smallest divisor as soon as remainder comes out to be zero. Since we are only interested in first smallest divisor and not all divisors of a given number, so jump out of the for loop using break statement without further going for the next iteration of for loop.
Here, break is different from exit. Former jumps the control out of the loop while exit stops the execution of the entire program.