×
☰ Menu

break and continue statements in C

 

The break Statement :

We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. 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 statement.


Program on while loop using break statement

#include<stdio.h>
#include<conio.h>
int main()
{
int num, i ;
printf ( "Enter a number " ) ;
scanf ( "%d", &num ) ;
i = 2 ;
/*start of while loop;*/
while (i<=num-1)
{
if (num%i==0)
{
printf ( "Not a prime number" ) ;
break ;
}
i++ ;
}
if (i==num)
printf ( "Prime number" ) ;
getch();
}

 

Output: 

Enter a number 11
Prime number
--------------------------------
Process exited after 4.762 seconds with return value 0
Press any key to continue . . .

 


 


The continue Statement 


In some programming situations, we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. When a continue is encountered inside any loop, control automatically passes to the beginning of the loop. 

A continue is usually associated with an if.

 

Program on while loop using continue statement:

#include<stdio.h>
#include<conio.h>
int main()
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
 for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
getch();
}

Output:

1 2
2 1
--------------------------------
Process exited after 5.241 seconds with a return value 0
Press any key to continue . . .