C programming tutorial

                 

PREVIOUS                                                                                   NEXT CHAPTER

 

break statement in C


sometimes in real world c programming there is need to exit loop before its completion.break allows us to do this.When break is encoutered in a loop , control automatically passes to first statement after that loop

Following program will explain its use.Its a program to find whether number is prime or not.

 

To find whether number is prime we just have to check whether remainder is non zero when divided by all numbers from 2 to one less than itself.If any one time remainder comes to be zero, number won't be prime.

#include<stdio.h>

main()

{

int num;

printf("Enter number");

scanf("%d",&a);

for(int i=2;i<=num-1;i++)

{

if( num%i==0)

{

printf("number not prime");

break;

}

}

if(i==num)

print("number is prime");

}

Remainder is checked inside loop whether it is zero or not.If remainder comes to be zero then 'number not prime' will be printed and break statement will exit loop and control will go to the first statement after loop.

Since In this case loop would exit before its completion,therfore i will not be not be equal to num.statement inside if will not execute.program will end.

 

If remainder does not comes zero in all iterations.num will be equal to i after last iteration.'number is prime' will be printed as output,

 

 


                  PREVIOUS                                                                                   NEXT CHAPTER