Skip Loop Iterations with continue Statement
In this step, you'll learn how to use the continue
statement in C++ to skip the current iteration of a loop and move to the next iteration. The continue
statement allows you to selectively skip parts of a loop based on specific conditions.
First, navigate to the project directory and create a new C++ file:
cd ~/project
touch continue_statement.cpp
Open the continue_statement.cpp
file in the WebIDE and add the following code to explore different ways of using the continue
statement:
#include <iostream>
int main() {
// Skipping even numbers in a loop
std::cout << "Printing odd numbers between 1 and 10:" << std::endl;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
std::cout << i << " ";
}
std::cout << std::endl;
// Filtering out negative numbers in a sum calculation
int sum = 0;
int numbers[] = {5, -3, 10, -7, 8, -2, 15};
int arraySize = sizeof(numbers) / sizeof(numbers[0]);
std::cout << "\nCalculating sum of positive numbers:" << std::endl;
for (int j = 0; j < arraySize; j++) {
if (numbers[j] < 0) {
continue; // Skip negative numbers
}
sum += numbers[j];
std::cout << "Added: " << numbers[j] << ", Current Sum: " << sum << std::endl;
}
std::cout << "Final Sum of Positive Numbers: " << sum << std::endl;
return 0;
}
Compile and run the program:
g++ continue_statement.cpp -o continue_statement
./continue_statement
Example output:
Printing odd numbers between 1 and 10:
1 3 5 7 9
Calculating sum of positive numbers:
Added: 5, Current Sum: 5
Added: 10, Current Sum: 15
Added: 8, Current Sum: 23
Added: 15, Current Sum: 38
Final Sum of Positive Numbers: 38
Key characteristics of the continue
statement:
- Skips the rest of the current loop iteration
- Transfers control to the next iteration of the loop
- Can be used in
for
, while
, and do-while
loops
- Useful for filtering or conditional processing
Important continue
statement uses:
- Skipping specific iterations based on conditions
- Filtering data in loops
- Avoiding unnecessary computations
- Simplifying loop logic