Continue Statement in C Language:
Continue is a keyword. By using continue we can skip the statement from the loop body. Using continue is always optional but it should be placed within the loop body only. In an implementation where we know the maximum number of repetition but some condition is there we need to skip the statement from loop body then we need to go for continue statement.
The continue statement provides a convenient way to immediately start the next iteration of the enclosing FOR, WHILE, or REPEAT loop. Whereas the BREAK statement exits from a loop, the continue statement exits only from the current loop iteration, proceeding immediately to the next iteration. The continue statement is almost always used with the if…else statement. For the for loop, the continue statement causes the conditional test and increment portions of the loop to execute. For the while and do-while loops, continue statement causes the program control to pass to the conditional tests.
How Does the Continue Statement Work in C Language?
Syntax: continue;
Example to Understand Continue Statement in C Language:
#include <stdio.h> int main () { int counter = 10; while (counter >= 0) { if (counter == 7) { counter--; continue; } printf ("%d ", counter); counter--; } return 0; }
Output:
if we do not place the counter– statement in the body of “if” then the value of counter would remain 7 indefinitely. The print statement is skipped when the counter value was 7.
Note: When the continue statement is executed within the loop body then control will pass back to the condition without executing the remaining statement.
Some tricky Questions Related to C Continue Statement.
Question1: What will be the output in the below program?
#include <stdio.h> int main() { int a = 10; while(a <= 25) { a += 2; if(a >15 && a < 20) continue; printf("%d ", a); } return 0; }
Output: 12 14 20 22 24 26
Question2: What will be the output in the below program?
#include <stdio.h> int main() { int a = 1; while(a <= 50) { printf("%d ", a); if(a >= 5 && a <= 35) continue; a = a+ 2; } return 0; }
Output: infinite loop
Question3: What will be the output in the below program?
#include <stdio.h> int main() { int a = 8; while(a <= 42); { a += 2; if(a >= 20 && a <= 30) continue; printf("%d", a); } return 0; }
Output:
Note: When the semicolon (;) is placed after the while then it becomes a dummy loop. When the dummy loop is created then the compiler will create an empty body without any statement and the current body becomes outside. Then automatically continue is placing outside then it becomes an error.