break keyword in C

The keyword break allows us to do this. When break is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an if

Example: Write a program to determine whether a number is prime or not. A prime number is one, which is divisible only by 1 or itself

main( ) 
{ 
 int num, i ; 
 printf ( "Enter a number " ) ; 
 scanf ( "%d", &num ) ; 
 i = 2 ; 
 while ( i <= num - 1 ) 
 { 
 if ( num % i == 0 ) 
 { 
 printf ( "Not a prime number" ) ; 
 break ; 
 } 
 i++ ; 
 } 

if ( i == num ) 
 printf ( "Prime number" ) ; 
} 

In this program the moment num % i turns out to be zero, (i.e. num is exactly divisible by i) the message “Not a prime number” is printed and the control breaks out of the while loop

The keyword break, breaks the control only from the while in which it is placed. Consider the following program, which illustrates this fact

main( ) 
{ 
 int i = 1 , j = 1 ; 
 while ( i++ <= 100 ) 
 { 
 while ( j++ <= 200 ) 
 { 
 if ( j == 150 ) 
 break ; 
 else 
 printf ( "%d %d\n", i, j ) ; 
 } 
}
}

Leave a Comment