The break statement in C Language With Example Program

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

break;

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 */

#include <stdio.h>

main( )

{

int div,num,i;

printf(“Enter any number:\n”);

scanf(“%d”,&num);

for (i=2;i<=num;++i)

{

if ((num % i) == 0)

{

printf(“Smallest divisor for number %d is %d”,num,i);

break;

}

}

}

OUTPUT

Enter any number:
9
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.

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: