Example of continue in C
Example 1: C Program to use continue statement in a single loop.
The continue statement can be used in for loop, while loop, and do-while loop.
C
// C program to explain the use // of continue statement with for loop #include <stdio.h> int main() { // for loop to print 1 to 8 for ( int i = 1; i <= 8; i++) { // when i = 4, the iteration will be skipped and for // will not be printed if (i == 4) { continue ; } printf ( "%d " , i); } printf ( "\n" ); int i = 0; // while loop to print 1 to 8 while (i < 8) { // when i = 4, the iteration will be skipped and for // will not be printed i++; if (i == 4) { continue ; } printf ( "%d " , i); } return 0; } |
1 2 3 5 6 7 8 1 2 3 5 6 7 8
Example 2: C Program to use continue in a nested loop
The continue statement will only work in a single loop at a time. So in the case of nested loops, we can use the continue statement to skip the current iteration of the inner loop when using nested loops.
C
// C program to explain the use // of continue statement with nested loops #include <stdio.h> int main() { // outer loop with 3 iterations for ( int i = 1; i <= 3; i++) { // inner loop to print integer 1 to 4 for ( int j = 0; j <= 4; j++) { // continue to skip printing number 3 if (j == 3) { continue ; } printf ( "%d " , j); } printf ( "\n" ); } return 0; } |
0 1 2 4 0 1 2 4 0 1 2 4
The continue skips the current iteration of the inner loop when it executes in the above program. As a result, the program is controlled by the inner loop update expression. In this way, 3 is never displayed in the output.
Continue Statement in C
The continue statement in C is a jump statement that is used to bring the program control to the start of the loop. We can use the continue statement in the while loop, for loop, or do..while loop to alter the normal flow of the program execution. Unlike break, it cannot be used with a C switch case.