C++ For Loop

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.

Tutorials dojo strip



How the for Loop Works

The for loop contains three main components, executed in a specific order:

  1. Initialization (Statement 1): Runs once before the loop starts.
  2. Condition (Statement 2): Evaluated before each iteration; the loop continues as long as this condition is true.
  3. Update (Statement 3): Executes after each iteration to modify loop variables.




Syntax

for (statement 1; statement 2; statement 3) {
    // Code to execute in the loop
}




Example: Counting Gears of a Motorcycle

#include <iostream>
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): Sets gear to 1 before the loop begins.
  • Condition (gear <= 5): The loop continues as long as gear is less than or equal to 5.
  • Update (gear++): Increments gear by 1 after each iteration.
    The output will display:
Gear: 1  
Gear: 2  
Gear: 3  
Gear: 4  
Gear: 5  




Example: Printing Even Numbers

This example demonstrates printing even values within a specific range.

#include <iostream>
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 as rpm is 10 or less.
  • Update (rpm = rpm + 2): Increases rpm by 2 after each iteration.
    The output will display:
0  
2  
4  
6  
8  
10  

Tutorials dojo strip
Scroll to Top