Home Tutorials C++ Tutorial For Loop
For Loop

For Loop


C++ For Loop

Definition: The for loop is a robust control flow statement used to repeat a block of code a specific number of times. It is particularly effective when you know exactly how many iterations are required before the loop begins.

Why: In any beginner C++ guide, the for loop is introduced alongside other control statements as the most concise way to manage loops. By grouping the initialization, condition, and increment into a single line, it reduces code clutter and minimizes the risk of creating infinite loops.


Syntax Structure

The for loop consists of three distinct parts separated by semicolons within parentheses:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

Example: Printing a Sequence

In this example, the loop starts at 1, checks if the number is less than or equal to 5, and increments the value after every print statement:

#include <iostream>
using namespace std;

int main() {
    // The loop runs exactly 5 times
    for (int i = 1; i <= 5; i++) {
        cout << i << endl;
    }

    return 0;
}

The Three Parameters of a For Loop

Parameter Execution Timing Purpose
Initialization Executed only once. Sets the starting value of the loop counter (e.g., int i = 1).
Condition Checked before every loop. Evaluates to true or false. If false, the loop ends immediately.
Increment Executed after every loop body. Updates the counter (e.g., i++) to move toward the end condition.

Key Notes

  • Scope of the Counter: If you declare the variable i inside the for loop (for(int i = 0...)), that variable only exists within the loop. It is destroyed once the loop finishes.
  • Nested Loops: You can place a for loop inside another for loop. This is commonly used for working with multi-dimensional data like grids or tables.
  • Array Iteration: for loops are the primary tool for traversing arrays. By using the counter as an index (array[i]), you can access every element in a list sequentially.
  • Infinite Loops: A for loop can become infinite if the condition is omitted or can never be false, such as for(;;). This is sometimes used in system programming but should be avoided by beginners.

🏋️ Test Yourself With Exercises

Take our quiz on For Loop to test your knowledge.

Browse Quizzes »