Break And Continue Statements With C
In C, "break" and "continue" are control statements that are used inside loops
to change the normal flow of the loop.
Break Statement:
The "break" is used to exit a loop Permanently. When the "break" statement is executed with inside a loop, the loop is terminated immediately, and the program continues to the code that comes after the loop can executed.
Program:
#include <stdio.h>
Int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
{
break; // terminate the loop when i becomes 5
}
printf("%d\n", i);
}
return 0;
}
Int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i == 5)
{
break; // terminate the loop when i becomes 5
}
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
4
2
3
4
Continue Statement:
A "continue" is used to skip the current iteration of the loop and move on to the next iteration. When the "continue" statement is executed inside a loop, the program can skips any remaining statements in the loop's body and immediately moves on to the next iteration of the loop.
Program:
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i % 2 == 0)
{
continue; // skip the even numbers
}
printf("%d\n", i);
}
return 0;
}
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
if(i % 2 == 0)
{
continue; // skip the even numbers
}
printf("%d\n", i);
}
return 0;
}
Output:
1
3
5
7
9
3
5
7
9