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

C++

Example: Counting Gears of a Motorcycle

C++

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.

Output

C++

Example: Printing Even Numbers

This example demonstrates printing even values within a specific range.

C++

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.

Output

C++

Tutorials dojo strip