
What is continue statement in C?
In C programming, continue is a keyword used in loop control statements to skip the remaining statements in the current iteration of the loop and continue with the next iteration.
The continue statement is used in loops, such as for, while, and do-while, to skip the current iteration’s remaining statements and jump directly to the next iteration’s evaluation.
Examples of continue statement in C:
1. continue statement in for loop
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skip iteration when i is 3
}
printf("%d ", i);
}
return 0;
}Output:
1 2 4 5Explanation;
In above example, we are using a for loop to print numbers from 1 to 5. However, when i is equal to 3, we are using the continue statement to skip that iteration and move on to the next one. As a result, the number 3 is not printed.
2. continue statement in while loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
if (i == 3) {
i++;
continue; // skip iteration when i is 3
}
printf("%d ", i);
i++;
}
return 0;
}Output:
1 2 4 5Explanation;
In above example, we are using a while loop to print numbers from 1 to 5. When i is equal to 3, we are using the continue statement to skip that iteration and move on to the next one. We are also incrementing i before using the continue statement, to avoid an infinite loop. As a result, the number 3 is not printed.
3. continue statement in do while loop
#include <stdio.h>
int main() {
int i = 1;
do {
if (i == 3) {
i++;
continue; // skip iteration when i is 3
}
printf("%d ", i);
i++;
} while (i <= 5);
return 0;
}Output:
1 2 4 5Explanation;
In above example, we are using a do while loop to print numbers from 1 to 5. When i is equal to 3, we are using the continue statement to skip that iteration and move on to the next one. We are also incrementing i before using the continue statement, to avoid an infinite loop. As a result, the number 3 is not printed.
Rules to be followed when using continue statement in C:
- The
continuestatement can only be used inside loops such asfor,while, ordo whileloops. - When the
continuestatement is executed, it skips the remaining statements inside the loop for that particular iteration and moves on to the next iteration. - The
continuestatement can be used to skip a particular iteration of the loop based on some condition. It is often used in conjunction with anifstatement to skip a particular iteration based on a certain condition. - When using the
continuestatement, be careful to avoid infinite loops. Make sure that the condition for terminating the loop will eventually be met, even if some iterations are skipped usingcontinue. - In some cases, using
continuecan make your code harder to read and understand. Consider using other control structures such asbreakor restructuring your code if the use ofcontinuemakes your code less clear.