Lesson 33 of 60 – Nested Loops in C++
55%

Nested Loops in C++

A nested loop is a loop placed inside another loop. The outer loop controls the larger repetition, while the inner loop runs completely for each iteration of the outer loop.

Note: Nested loops are commonly used for tables, patterns, matrices, grids, and problems where one repetition happens inside another repetition.

1. What is a Nested Loop?

A loop inside another loop is called a nested loop.

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 3; j++) {

        std::cout << i << " " << j << std::endl;
    }
}

Here, the outer for loop contains another for loop.

2. Basic Structure of Nested Loops

for (initialization; condition; update) {

    for (initialization; condition; update) {

        // inner loop statements

    }

}

The inner loop is executed for every iteration of the outer loop.

3. Simple Nested Loop Example

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 3; j++) {

        std::cout << j << " ";
    }

    std::cout << std::endl;
}

Output:

1 2 3
1 2 3
1 2 3

The inner loop runs three times for each outer loop iteration.

4. How Nested Loops Work

Consider:

for (int i = 1; i <= 2; i++) {

    for (int j = 1; j <= 3; j++) {

        std::cout << i << "," << j << std::endl;
    }
}

The execution is:

  1. Outer loop starts with i = 1.
  2. Inner loop runs with j = 1, 2, 3.
  3. Outer loop changes to i = 2.
  4. Inner loop again runs with j = 1, 2, 3.

5. Nested Loop with Rows and Columns

for (int row = 1; row <= 3; row++) {

    for (int column = 1; column <= 4; column++) {

        std::cout << "* ";
    }

    std::cout << std::endl;
}

Output:

* * * *
* * * *
* * * *

The outer loop represents rows and the inner loop represents columns.

6. Printing a Square Pattern

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= 5; j++) {

        std::cout << "* ";
    }

    std::cout << std::endl;
}

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

7. Number Pattern

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= 5; j++) {

        std::cout << j << " ";
    }

    std::cout << std::endl;
}

Output:

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

8. Increasing Number Pattern

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= i; j++) {

        std::cout << j << " ";
    }

    std::cout << std::endl;
}

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

9. Star Triangle Pattern

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= i; j++) {

        std::cout << "* ";
    }

    std::cout << std::endl;
}

Output:

*
* *
* * *
* * * *
* * * * *

10. Reverse Star Pattern

for (int i = 5; i >= 1; i--) {

    for (int j = 1; j <= i; j++) {

        std::cout << "* ";
    }

    std::cout << std::endl;
}

Output:

* * * * *
* * * *
* * *
* *
*

11. Multiplication Tables Using Nested Loops

for (int i = 1; i <= 3; i++) {

    std::cout << "Table of " << i
              << std::endl;

    for (int j = 1; j <= 10; j++) {

        std::cout << i
                  << " x "
                  << j
                  << " = "
                  << i * j
                  << std::endl;
    }

    std::cout << std::endl;
}

The outer loop selects the table and the inner loop generates its multiplication values.

12. Nested while Loops

int i = 1;

while (i <= 3) {

    int j = 1;

    while (j <= 3) {

        std::cout << j << " ";

        j++;
    }

    std::cout << std::endl;

    i++;
}

Nested loops are not limited to for loops. A while loop can also contain another while loop.

13. Nested do-while Loops

int i = 1;

do {

    int j = 1;

    do {

        std::cout << j << " ";

        j++;

    } while (j <= 3);

    std::cout << std::endl;

    i++;

} while (i <= 3);

A do-while loop can also be placed inside another do-while loop.

14. Mixed Nested Loops

Different types of loops can be nested together.

for (int i = 1; i <= 3; i++) {

    int j = 1;

    while (j <= 3) {

        std::cout << i
                  << ","
                  << j
                  << std::endl;

        j++;
    }
}

15. Nested Loops with if Statement

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= 5; j++) {

        if (j == 3) {
            std::cout << "X ";
        }
        else {
            std::cout << "* ";
        }
    }

    std::cout << std::endl;
}

An if statement can control what is displayed inside the inner loop.

16. Nested Loops with break

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 5; j++) {

        if (j == 3) {
            break;
        }

        std::cout << j << " ";
    }

    std::cout << std::endl;
}

The break statement terminates only the inner loop.

17. Nested Loops with continue

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 5; j++) {

        if (j == 3) {
            continue;
        }

        std::cout << j << " ";
    }

    std::cout << std::endl;
}

The continue statement skips 3 in the inner loop while the remaining values continue to execute.

18. Nested Loop for Matrix

int matrix[2][3] = {
    {10, 20, 30},
    {40, 50, 60}
};

for (int i = 0; i < 2; i++) {

    for (int j = 0; j < 3; j++) {

        std::cout << matrix[i][j] << " ";
    }

    std::cout << std::endl;
}

Output:

10 20 30
40 50 60

Nested loops are commonly used to process two-dimensional arrays.

19. Matrix Addition

int a[2][2] = {
    {1, 2},
    {3, 4}
};

int b[2][2] = {
    {5, 6},
    {7, 8}
};

for (int i = 0; i < 2; i++) {

    for (int j = 0; j < 2; j++) {

        std::cout << a[i][j] + b[i][j]
                  << " ";
    }

    std::cout << std::endl;
}

The outer loop handles rows and the inner loop handles columns.

20. Nested Loop for Coordinates

for (int x = 1; x <= 3; x++) {

    for (int y = 1; y <= 3; y++) {

        std::cout << "("
                  << x
                  << ","
                  << y
                  << ") "
                  ;
    }

    std::cout << std::endl;
}

Nested loops can generate combinations of rows and columns or coordinate values.

21. Nested Loop for Number Pairs

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 3; j++) {

        std::cout << i
                  << " + "
                  << j
                  << " = "
                  << i + j
                  << std::endl;
    }
}

The inner loop creates different pairs for each value of the outer loop.

22. Multiplication Grid

for (int i = 1; i <= 5; i++) {

    for (int j = 1; j <= 5; j++) {

        std::cout << i * j << "\t";
    }

    std::cout << std::endl;
}

Output:

1    2    3    4    5
2    4    6    8    10
3    6    9    12   15
4    8    12   16   20
5    10   15   20   25

The outer loop controls rows and the inner loop controls columns.

23. Counting Total Iterations

for (int i = 1; i <= 3; i++) {

    for (int j = 1; j <= 4; j++) {

        std::cout << "Hello"
                  << std::endl;
    }
}

The outer loop runs 3 times and the inner loop runs 4 times for each outer iteration.

Total executions:

3 × 4 = 12

24. Nested Loop with User Input

int rows, columns;

std::cout << "Enter rows: ";
std::cin >> rows;

std::cout << "Enter columns: ";
std::cin >> columns;

for (int i = 1; i <= rows; i++) {

    for (int j = 1; j <= columns; j++) {

        std::cout << "* ";
    }

    std::cout << std::endl;
}

The user can decide how many rows and columns should be displayed.

25. Nested Loop for Student Marks

int marks[3][3] = {
    {70, 80, 90},
    {60, 75, 85},
    {88, 92, 95}
};

for (int student = 0; student < 3; student++) {

    std::cout << "Student "
              << student + 1
              << ": ";

    for (int subject = 0; subject < 3; subject++) {

        std::cout << marks[student][subject]
                  << " ";
    }

    std::cout << std::endl;
}

The outer loop represents students and the inner loop represents subjects.

26. Common Mistakes in Nested Loops

  • Using the wrong condition in the inner loop.
  • Forgetting to update the inner loop variable.
  • Using the same variable incorrectly in both loops.
  • Forgetting braces and creating confusing code.
  • Using break when only one specific operation should be skipped.
  • Creating unnecessary deep nesting.
  • Accessing array indexes outside their valid range.
for (int i = 0; i < 3; i++) {

    for (int j = 0; j < 3; j++) {

        std::cout << i
                  << ","
                  << j
                  << std::endl;
    }
}

27. Practical Pattern Program

#include <iostream>

int main() {

    int rows;

    std::cout << "Enter number of rows: ";
    std::cin >> rows;

    for (int i = 1; i <= rows; i++) {

        for (int j = 1; j <= i; j++) {

            std::cout << "* ";
        }

        std::cout << std::endl;
    }

    return 0;
}

If the user enters 5, the program displays a triangle pattern.

28. Practical Matrix Program

#include <iostream>

int main() {

    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (int i = 0; i < 3; i++) {

        for (int j = 0; j < 3; j++) {

            std::cout << matrix[i][j]
                      << " ";
        }

        std::cout << std::endl;
    }

    return 0;
}

This program uses nested loops to display a 3×3 matrix.

29. Best Practices for Nested Loops

  • Use meaningful variable names such as row and column.
  • Keep the inner loop simple and focused.
  • Initialize the inner loop correctly for every outer iteration.
  • Always update loop variables properly.
  • Use nested loops when the problem naturally has multiple levels of repetition.
  • Avoid unnecessary deep nesting because it can make code harder to understand.
  • Be careful when using break and continue inside nested loops.

30. Nested Loops – Final Summary

Concept Meaning
Nested Loop A loop placed inside another loop.
Outer Loop Controls the larger repetition.
Inner Loop Runs for each iteration of the outer loop.
Pattern Nested loops are commonly used to create patterns.
Matrix Nested loops can process rows and columns.
break Terminates the nearest enclosing loop.
continue Skips the current iteration of the nearest enclosing loop.
for (int row = 1; row <= 3; row++) {

    for (int column = 1; column <= 3; column++) {

        // inner loop code
    }
}

📌 Key Points

  • A nested loop is a loop inside another loop.
  • The outer loop controls the main repetition.
  • The inner loop runs completely for every outer loop iteration.
  • Nested loops can be created using for, while, and do-while loops.
  • They are useful for patterns and tables.
  • They are commonly used with two-dimensional arrays and matrices.
  • Nested loops can be combined with if statements.
  • break affects the nearest enclosing loop.
  • continue affects the nearest enclosing loop.
  • Always initialize and update inner loop variables correctly.

🧠 Quick Quiz

Question: What is a nested loop in C++?