Break & Continue

break and continue statements can be used with any of the three types of loops in C - while, do ... while, for. They can change the normal execution of a loop by terminating the loop early or skip some statements in an iteration.

break

The break statement is used for early termination of a loop. A program will exit the loop when it encounters a break statement and the control is transferred to the next statement after the loop.

Example

#include <stdio.h>

int main() {
int i;

for (i=1; i <= 10; ++i) {

	if (i==5) break;
	printf("%d \\n",i);
} 

return 0;
}

In the above example, the loop will exit when the value of i equals 5. Only the numbers from 1 to 4 will be printed in this case.

continue

The continue statement is used to skip the current iteration of the loop. Any statements after the continue won't be executed and the control will be passed on to the beginning of the loop.

Example

#include <stdio.h>

int main() {
int i;

for (i=1; i <= 10; ++i) {

	if (i==5) continue;
	printf("%d \\n",i);
} 

return 0;
}

In the above example the printf statement is skipped when the value of i equals 5. So all the numbers except number 5 will be printed.

Last Updated: 07-June-2013


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.