In many situations we need to come out of the loop in the
middle based upon some conditions.
In C, we can use break
keyword to come out of loop. After the break statement is executed control goes
to the first statement after loop.
#include <stdio.h>
void main()
{
int i=0;
while(i<10)
{
printf("%d",i);
if (i==5)
break;
i++;
}
}
In above example, we have used break statement to come out
of while loop. Above loop will print the values from 0 to 5.
Similarly we have continue
keyword that can be used to get the control to the beginning of the loop. After
continue statement is executed, all the statements after continue are skipped
and control goes to the condition statement in the loop.
Example on continue keyword
in C.
#include <stdio.h>
void main()
{
int i=0;
while(i<10)
{
i++;
if (i%2==0)
continue;
printf("%d",i);
}
}
In above example we have used continue statement to print only odd numbers. If the number is
even, control goes to the beginning of the loop.
No comments:
Post a Comment
Leave your valuable feedback. Your thoughts do matter to us.