Sep 28

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.

Syntax:

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 loop  and also in switch statement.

Example

program to calculate the first smallest divisior of a number

#include<stdio.h>

void main()

{

int div,num,i;

printf(”enter any no.\n”);

scanf(”%d”,&num);

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

{

if(num%i==0)

{

printf(”smallest divisior is %d”,i);

break;

}

}

}

Output

enter any no.

9

smallest divisior is 3

In 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 interested in first smallest divisor and not all divisor of a given number so jump out of for loop using break statement without further going for next iteration of for loop.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Blogplay
  • LinkedIn
  • MySpace
  • Reddit
  • RSS
  • Twitter

written by Shweta