The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.
C – Continue statement
Syntax:
continue;
Flow diagram of continue statement
Example: continue statement inside for loop
#include <stdio.h> int main() { for (int j=0; j<=8; j++) { if (j==4) { /* The continue statement is encountered when * the value of j is equal to 4. */ continue; } /* This print statement would not execute for the * loop iteration where j ==4 because in that case * this statement would be skipped. */ printf("%d ", j); } return 0; }
Output:
0 1 2 3 5 6 7 8
Value 4 is missing in the output, why? When the value of variable j is 4, the program encountered a continue statement, which makes the control to jump at the beginning of the for loop for next iteration, skipping the statements for current iteration (that’s the reason printf didn’t execute when j is equal to 4).
Example: Use of continue in While loop
In this example we are using continue
inside while loop. When using while or do-while loop you need to place an increment or decrement statement just above the continue
so that the counter value is changed for the next iteration. For example, if we do not place counter– statement in the body of “if” then the value of counter would remain 7 indefinitely.
#include <stdio.h> int main() { int counter=10; while (counter >=0) { if (counter==7) { counter--; continue; } printf("%d ", counter); counter--; } return 0; }
Output:
10 9 8 6 5 4 3 2 1 0
The print statement is skipped when counter value was 7.
Another Example of continue in do-While loop
#include <stdio.h> int main() { int j=0; do { if (j==7) { j++; continue; } printf("%d ", j); j++; }while(j<10); return 0; }
Output:
0 1 2 3 4 5 6 8 9
Leave a Reply