C++ continue Keyword
The continue keyword in C++ is used to skip the current iteration of a loop and proceed to the next iteration. It is commonly used in for, while, and do-while loops to bypass the remaining code in the loop body for the current iteration when a specific condition is met.
Using continue helps manage control flow more effectively by selectively skipping certain iterations while continuing the overall loop execution.
Syntax
</>
Copy
loop {
if (condition) {
continue;
}
// Code to execute if the condition is false
}
- loop
- Any loop structure like
for,while, ordo-while. - condition
- The condition that determines whether to skip the rest of the current iteration.
- continue
- The keyword that causes the loop to skip to the next iteration.
Examples
Example 1: Skipping Even Numbers in a for Loop
This example demonstrates using continue to skip even numbers in a for loop.
</>
Copy
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
cout << i << " ";
}
return 0;
}
Output:
1 3 5 7 9
Explanation:
- The loop iterates from
1to10. - If the current number
iis even (i % 2 == 0), thecontinuestatement is executed, skipping the remaining code for that iteration. - As a result, only odd numbers are printed to the console.
Example 2: Skipping Specific Values in a while Loop
This example shows how to use continue in a while loop to skip specific values.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 10) {
++i;
if (i == 5 || i == 7) {
continue; // Skip 5 and 7
}
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 6 8 9 10
Explanation:
- The
whileloop iterates from1to10. - If
iequals5or7, thecontinuestatement is executed, skipping the current iteration. - All other numbers are printed, except
5and7.
Example 3: Using continue in a do-while Loop
This example demonstrates how to use continue in a do-while loop to skip specific iterations.
</>
Copy
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
++i;
if (i % 3 == 0) {
continue; // Skip multiples of 3
}
cout << i << " ";
} while (i < 10);
return 0;
}
Output:
1 2 4 5 7 8 10
Explanation:
- The
do-whileloop iterates from1to10. - If
iis a multiple of3, thecontinuestatement skips the current iteration. - All numbers that are not multiples of
3are printed to the console.
Key Points about continue Keyword
- The
continuekeyword skips the rest of the loop body for the current iteration and moves to the next iteration. - It can be used in
for,while, anddo-whileloops. - It is useful for selectively skipping iterations based on specific conditions.
- Using
continueimproves readability and control flow in loops where certain conditions require bypassing further execution.
