---
title: 5.4 Nested Loops
description: "A nested loop is a loop placed inside the body of another loop. The inner loop executes completely for each iteration of the outer loop. Nested loops are commonly used when working with two-dimensional data, generating tables, processing matrices, and…"
url: "https://edcret.in/docs/cpp-programming/loops/5-4-nested-loops/"
updated: "2026-09-06"
category: C++ Programming / Loops
---

# 5.4 Nested Loops

A nested loop is a loop placed inside the body of another loop. The inner loop executes completely for each iteration of the outer loop.

Nested loops are commonly used when working with two-dimensional data, generating tables, processing matrices, and performing repeated operations across multiple dimensions.

## Source Code

```
#include <iostream>

int main()
{
    for (int row = 1; row <= 3; ++row)
    {
        for (int column = 1; column <= 4; ++column)
        {
            std::cout << row << "," << column << "  ";
        }

        std::cout << '\n';
    }

    return 0;
}
```

## Output

```
1,1  1,2  1,3  1,4
2,1  2,2  2,3  2,4
3,1  3,2  3,3  3,4
```

## Explanation

- The outer `for` loop controls the value of `row`.
- The inner `for` loop controls the value of `column`.
- For every iteration of the outer loop, the inner loop executes all of its iterations.
- When `row` is `1`, the inner loop runs with `column` values from `1` through `4`.
- The outer loop then increments `row` to `2`, and the inner loop starts again from `column = 1`.
- This process continues until the outer loop condition becomes `false`.
- The inner loop is completely executed before the outer loop proceeds to its next iteration.
- Nested loops can contain other loop types, such as `while` or `do-while` loops.
- `return 0;` terminates the program successfully.
