The For Loop in C++

The for loop is used when the number of iterations is known. It allows you to execute a block of code a specific number of times.

Syntax of the for Loop

for (initialization; condition; increment) {
    // Code to execute
}

Example: Using the for Loop

#include <iostream>

int main() {
    for (int i = 1; i <= 5; i++) {
        std::cout << "Iteration: " << i << std::endl;
    }
    return 0;
}

Output:

Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

Explanation: The loop initializes i to 1, checks if i <= 5, executes the loop body, and then increments i by 1 in each iteration.

Key Takeaways

  • The for loop is concise and includes initialization, condition, and increment/decrement in one line.
  • Ideal when the number of iterations is known beforehand.
  • Ensure the loop condition will eventually become false to prevent infinite loops.