Learn C Language : Break, Continue Statement

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.Keyword break allow us to do this.When the keyword break is encountered inside the any c loop, control automatically passes to the first statement after the loop.A break is usually associated with an if.

A simple program which demonstrates the use of break statement:

main()
{
int num,i=2;
printf(“Enter a number”);
scanf(“%d”,&num);
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.

(1) It jumped out because the number proved to be not a prime.
(2) The loop came to an end because the value of i became equal to num.

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 the keyword continue is encountered inside any C loop, control automatically passes to the beginning of the loop.A continue is usually associated with an if.

A simple program which demonstrates the use of continue statement:

main()
{
int j,i;
for(i=1; 2 >= i; i++)
{
for(j=1; 2 <= j; j++)
{
if(i == j)
continue;
printf(“%d %d”,i,j);
}
}
}

Output :
1 2
2 1

 

Note that when the value of i equals that of j, the continue statement takes the control to the for loop(inner) bypassing rest of the statements pending execution in the for loop(inner).

Leave a Comment