continue statement in c
The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.Syntax:
ccontinue;
When the continue statement is encountered within a loop, the following happens:- The remaining code inside the current iteration of the loop is skipped.
2. The loop control variable (e.g., the iterator in a for loop) is updated (if applicable).
3. The loop condition is checked again to determine whether to continue with the next iteration or exit the loop.
- Using
continue
in afor
loop - :
cfor (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip iteration when i is 3
}
printf("%d\n", i);
}
Output:
In this example, when i is equal to 3, the continue statement is encountered, and the loop skips the rest of the code inside the current iteration, moving on to the next iteration.1 2 4 5
- Using
continue
in awhile
loop - :
cint i = 1;
while (i <= 5) {
if (i == 3) {
i++; // Don't forget to update the loop control variable
continue; // Skip iteration when i is 3
}
printf("%d\n", i);
i++; // Increment the loop control variable
}
Output:
In this while loop, we manually increment the loop control variable i when we use continue to ensure that the loop makes progress and doesn't result in an infinite loop.1 2 4 5
- Using
continue
in ado-while
loop
cint i = 1;
do {
if (i == 3) {
i++; // Don't forget to update the loop control variable
continue; // Skip iteration when i is 3
}
printf("%d\n", i);
i++; // Increment the loop control variable
} while (i <= 5);
Output:
1 2 4 5
Similar to the while loop example, in a do-while loop, you need to manually update the loop control variable inside the loop when using continue.
0 Comments