When you know the exact number of times you want to execute a block of code, the for
loop is the best choice. It provides a clear structure for initializing variables, setting conditions, and updating values—all within a single line.
How the for Loop Works
The for
loop contains three main components, executed in a specific order:
- Initialization (Statement 1): Runs once before the loop starts.
- Condition (Statement 2): Evaluated before each iteration; the loop continues as long as this condition is true.
- Update (Statement 3): Executes after each iteration to modify loop variables.
Syntax
C++
x
for (statement 1; statement 2; statement 3) {
// Code to execute in the loop
}
Example: Counting Gears of a Motorcycle
C++
using namespace std;
int main() {
for (int gear = 1; gear <= 5; gear++) {
cout << "Gear: " << gear << "\n";
}
return 0;
}
Explanation of the Example
- Initialization (
int gear = 1
): Setsgear
to 1 before the loop begins. - Condition (
gear <= 5
): The loop continues as long asgear
is less than or equal to 5. - Update (
gear++
): Incrementsgear
by 1 after each iteration.
Output
C++
Gear: 1
Gear: 2
Gear: 3
Gear: 4
Gear: 5
Example: Printing Even Numbers
This example demonstrates printing even values within a specific range.
C++
using namespace std;
int main() {
for (int rpm = 0; rpm <= 10; rpm = rpm + 2) {
cout << rpm << "\n";
}
return 0;
}
How It Works
- Initialization (
int rpm = 0
): Starts with an RPM value of 0. - Condition (
rpm <= 10
): The loop runs as long asrpm
is 10 or less. - Update (
rpm = rpm + 2
): Increasesrpm
by 2 after each iteration.
Output
C++
0
2
4
6
8
10