Coming Soon

This lesson is currently being developed

For statements

Master the most common loop construct in C++.

Control Flow
Chapter
Beginner
Difficulty
45min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

8.10 — For statements

In this lesson, you'll learn about for loops, the most commonly used loop construct in C++. You'll master their syntax, understand when to use them, and discover why they're perfect for many repetitive tasks.

What is a for loop?

A for loop is a control flow statement that combines initialization, condition testing, and update in a single, compact line. It's ideal when you know how many times you want to repeat something or when working with sequences.

Syntax:

for (initialization; condition; update)
{
    // Loop body - code to execute repeatedly
}

Components:

  • Initialization: Executed once before the loop starts
  • Condition: Checked before each iteration; loop continues while true
  • Update: Executed after each iteration

Basic for loop example

#include <iostream>

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

Output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop finished!

How for loops work

Let's break down the execution:

for (int i = 0; i < 3; ++i)
{
    std::cout << "i = " << i << std::endl;
}

Step-by-step execution:

  1. Initialize: int i = 0 (i becomes 0)
  2. Check condition: i < 3 (0 < 3 is true, continue)
  3. Execute body: Print "i = 0"
  4. Update: ++i (i becomes 1)
  5. Check condition: i < 3 (1 < 3 is true, continue)
  6. Execute body: Print "i = 1"
  7. Update: ++i (i becomes 2)
  8. Check condition: i < 3 (2 < 3 is true, continue)
  9. Execute body: Print "i = 2"
  10. Update: ++i (i becomes 3)
  11. Check condition: i < 3 (3 < 3 is false, exit loop)

For loop vs while loop

Same logic, different syntax:

Using a while loop:

#include <iostream>

int main()
{
    // While loop equivalent
    int i = 0;                    // Initialization
    while (i < 5)                 // Condition
    {
        std::cout << i << " ";
        ++i;                      // Update
    }
    
    return 0;
}

Using a for loop:

#include <iostream>

int main()
{
    // For loop - more compact
    for (int i = 0; i < 5; ++i)   // Init, condition, update in one line
    {
        std::cout << i << " ";
    }
    
    return 0;
}

Both produce: 0 1 2 3 4

The for loop is more compact and keeps all loop control in one place.

Common for loop patterns

Pattern 1: Counting up

#include <iostream>

int main()
{
    // Count from 1 to 10
    for (int count = 1; count <= 10; ++count)
    {
        std::cout << count << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10

Pattern 2: Counting down

#include <iostream>

int main()
{
    // Countdown from 10 to 1
    for (int countdown = 10; countdown >= 1; --countdown)
    {
        std::cout << countdown << " ";
    }
    std::cout << "Blast off!" << std::endl;
    
    return 0;
}

Output: 10 9 8 7 6 5 4 3 2 1 Blast off!

Pattern 3: Skip counting

#include <iostream>

int main()
{
    // Count by 2s
    for (int i = 0; i <= 20; i += 2)
    {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    // Count by 5s
    for (int i = 5; i <= 50; i += 5)
    {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Output:

0 2 4 6 8 10 12 14 16 18 20 
5 10 15 20 25 30 35 40 45 50 

Pattern 4: Processing sequences

#include <iostream>

int main()
{
    // Print ASCII characters
    for (char c = 'A'; c <= 'Z'; ++c)
    {
        std::cout << c << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Practical examples

Example 1: Multiplication table

#include <iostream>

int main()
{
    int number;
    std::cout << "Enter a number for multiplication table: ";
    std::cin >> number;
    
    std::cout << "Multiplication table for " << number << ":\n";
    
    for (int i = 1; i <= 12; ++i)
    {
        std::cout << number << " x " << i << " = " << (number * i) << std::endl;
    }
    
    return 0;
}

Sample Output:

Enter a number for multiplication table: 7
Multiplication table for 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
7 x 11 = 77
7 x 12 = 84

Example 2: Sum and average calculator

#include <iostream>

int main()
{
    int count;
    std::cout << "How many numbers do you want to enter? ";
    std::cin >> count;
    
    double sum = 0.0;
    
    for (int i = 1; i <= count; ++i)
    {
        double number;
        std::cout << "Enter number " << i << ": ";
        std::cin >> number;
        sum += number;
    }
    
    double average = sum / count;
    
    std::cout << "Sum: " << sum << std::endl;
    std::cout << "Average: " << average << std::endl;
    
    return 0;
}

Sample Output:

How many numbers do you want to enter? 4
Enter number 1: 10
Enter number 2: 20
Enter number 3: 15
Enter number 4: 25
Sum: 70
Average: 17.5

Example 3: Factorial calculator

#include <iostream>

int main()
{
    int n;
    std::cout << "Enter a positive integer: ";
    std::cin >> n;
    
    if (n < 0)
    {
        std::cout << "Factorial is not defined for negative numbers.\n";
        return 1;
    }
    
    long long factorial = 1;
    
    for (int i = 1; i <= n; ++i)
    {
        factorial *= i;
    }
    
    std::cout << n << "! = " << factorial << std::endl;
    
    return 0;
}

Sample Output:

Enter a positive integer: 6
6! = 720

Example 4: Number pattern generator

#include <iostream>

int main()
{
    int rows = 5;
    
    std::cout << "Number triangle:\n";
    for (int i = 1; i <= rows; ++i)
    {
        for (int j = 1; j <= i; ++j)
        {
            std::cout << j << " ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

Output:

Number triangle:
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

Nested for loops

For loops can be nested inside other for loops, which is useful for working with 2D patterns, tables, or grids.

Example 1: Multiplication table grid

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Multiplication Table (1-10):\n";
    
    // Print header
    std::cout << "   ";
    for (int col = 1; col <= 10; ++col)
    {
        std::cout << std::setw(4) << col;
    }
    std::cout << std::endl;
    
    // Print rows
    for (int row = 1; row <= 10; ++row)
    {
        std::cout << std::setw(3) << row;  // Row label
        
        for (int col = 1; col <= 10; ++col)
        {
            std::cout << std::setw(4) << (row * col);
        }
        std::cout << std::endl;
    }
    
    return 0;
}

Example 2: Star patterns

#include <iostream>

int main()
{
    int size = 5;
    
    // Right triangle
    std::cout << "Right triangle:\n";
    for (int i = 1; i <= size; ++i)
    {
        for (int j = 1; j <= i; ++j)
        {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }
    
    std::cout << std::endl;
    
    // Rectangle
    std::cout << "Rectangle:\n";
    for (int i = 1; i <= 4; ++i)
    {
        for (int j = 1; j <= 8; ++j)
        {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }
    
    return 0;
}

Output:

Right triangle:
* 
* * 
* * * 
* * * * 
* * * * * 

Rectangle:
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 
* * * * * * * * 

Variable scope in for loops

Variables declared in the for loop initialization are only accessible within the loop:

#include <iostream>

int main()
{
    for (int i = 0; i < 5; ++i)
    {
        std::cout << "i = " << i << std::endl;
        // i is accessible here
    }
    
    // std::cout << i << std::endl;  // ERROR: i is not accessible here
    
    // If you need i after the loop, declare it outside
    int j;
    for (j = 0; j < 3; ++j)
    {
        std::cout << "j = " << j << std::endl;
    }
    
    std::cout << "Final j = " << j << std::endl;  // j is accessible here
    
    return 0;
}

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
j = 0
j = 1
j = 2
Final j = 3

Advanced for loop variations

Empty sections

You can leave any section of the for loop empty:

#include <iostream>

int main()
{
    // Empty initialization (variable declared outside)
    int i = 0;
    for (; i < 5; ++i)
    {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    
    // Empty update (updated inside loop body)
    for (int j = 0; j < 10;)
    {
        std::cout << j << " ";
        j += 2;  // Update inside the loop
    }
    std::cout << std::endl;
    
    // Infinite loop (empty condition means always true)
    int count = 0;
    for (;;)  // Infinite loop
    {
        std::cout << count << " ";
        if (++count >= 5) break;  // Exit with break
    }
    std::cout << std::endl;
    
    return 0;
}

Multiple variables

#include <iostream>

int main()
{
    // Multiple variables in initialization and update
    for (int i = 0, j = 10; i <= j; ++i, --j)
    {
        std::cout << "i=" << i << ", j=" << j << std::endl;
    }
    
    return 0;
}

Output:

i=0, j=10
i=1, j=9
i=2, j=8
i=3, j=7
i=4, j=6
i=5, j=5

When to use for loops

Use for loops when:

  • You know the number of iterations in advance
  • You're working with sequences or ranges
  • You need a counter variable
  • You're iterating through arrays or containers
  • You're generating patterns or tables

Perfect for loop scenarios:

#include <iostream>

int main()
{
    // 1. Known number of iterations
    for (int i = 0; i < 10; ++i)
    {
        // Process exactly 10 items
    }
    
    // 2. Array processing (we'll learn about arrays later)
    int numbers[] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; ++i)
    {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;
    
    // 3. Mathematical sequences
    for (int i = 1; i <= 1000; i *= 2)
    {
        std::cout << i << " ";  // Powers of 2
    }
    std::cout << std::endl;
    
    return 0;
}

Common for loop mistakes

Mistake 1: Off-by-one errors

// WRONG - goes one too far
for (int i = 1; i <= 10; ++i)
{
    // This runs 10 times (1 through 10)
    // If you want exactly 10 iterations starting from 0, this is wrong
}

// CORRECT - for 10 iterations starting from 0
for (int i = 0; i < 10; ++i)
{
    // This runs 10 times (0 through 9)
}

Mistake 2: Modifying the loop variable incorrectly

#include <iostream>

int main()
{
    // Can cause confusion
    for (int i = 0; i < 10; ++i)
    {
        if (i == 5)
        {
            i = 8;  // Modifying loop variable inside loop
        }
        std::cout << i << " ";
    }
    // Output: 0 1 2 3 4 8 9 (skips 5, 6, 7)
    
    return 0;
}

Mistake 3: Wrong increment/decrement

// WRONG - infinite loop
for (int i = 10; i > 0; ++i)  // Incrementing when we should decrement
{
    std::cout << i << std::endl;  // i gets larger, never reaches 0
}

// CORRECT
for (int i = 10; i > 0; --i)  // Decrement to reach the exit condition
{
    std::cout << i << std::endl;
}

Best practices for for loops

1. Use meaningful variable names

// Good - clear purpose
for (int studentCount = 0; studentCount < totalStudents; ++studentCount)
{
    processStudent(studentCount);
}

// Acceptable for simple cases
for (int i = 0; i < 10; ++i)
{
    // Simple counting
}

2. Keep the loop condition simple

// Good - simple condition
for (int i = 0; i < maxItems; ++i)

// Avoid - complex condition
for (int i = 0; i < calculateDynamicMax() && isStillValid(); ++i)

3. Use const for the limit when possible

const int MAX_ITERATIONS = 100;
for (int i = 0; i < MAX_ITERATIONS; ++i)
{
    // Clear intent and prevents accidental modification
}

4. Prefer ++i over i++

// Better - pre-increment
for (int i = 0; i < 10; ++i)  // Slightly more efficient

// Also correct - post-increment
for (int i = 0; i < 10; i++)  // But creates temporary copy

For basic types like int, the difference is minimal, but it's good practice.

Summary

For loops provide compact and powerful iteration control:

Structure:

  • Initialization: Set up loop variables (runs once)
  • Condition: Test before each iteration (continues while true)
  • Update: Modify variables after each iteration

Key advantages:

  • Compact syntax keeps all loop control in one place
  • Perfect for known iteration counts
  • Excellent for working with sequences and ranges
  • Natural fit for array and container processing

Common patterns:

  • Counting up/down
  • Skip counting (increment by values other than 1)
  • Processing sequences
  • Generating patterns
  • Nested loops for 2D operations

Best practices:

  • Use meaningful variable names
  • Keep conditions simple
  • Watch for off-by-one errors
  • Prefer pre-increment (++i)
  • Use const for limits when possible

For loops are the most commonly used loop construct in C++ because they're perfect for the majority of repetitive tasks where you know how many iterations you need.

Quiz

  1. What are the three components of a for loop?
  2. When is each component of a for loop executed?
  3. What's the scope of a variable declared in the for loop initialization?
  4. What happens if you leave the condition section empty in a for loop?
  5. What's the difference between ++i and i++ in a for loop?

Practice exercises

  1. Prime number checker: Write a program that checks if a number is prime by testing divisibility from 2 to the square root of the number.

  2. Fibonacci sequence: Generate and print the first n numbers in the Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, ...).

  3. Diamond pattern: Create a program that prints a diamond shape using asterisks, with the size determined by user input.

  4. Grade statistics: Write a program that reads grades for a class and calculates statistics like average, highest, lowest, and the number of passing grades.

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion