0
0
C++programming~5 mins

Nested loops in C++

Choose your learning style9 modes available
Introduction

Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.

When you want to print a grid of stars or numbers.
When you need to check every pair of items in a list.
When you want to create patterns with rows and columns.
When you process multi-dimensional arrays like tables.
When you want to compare elements in two different lists.
Syntax
C++
for (initialization; condition; update) {
    for (initialization; condition; update) {
        // inner loop code
    }
    // outer loop code
}
The inner loop runs completely every time the outer loop runs once.
You can have more than two loops nested, but keep it simple to avoid confusion.
Examples
This prints pairs of numbers where the first number goes from 1 to 3 and the second from 1 to 2.
C++
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        std::cout << i << "," << j << " ";
    }
    std::cout << std::endl;
}
This prints a 4x4 square of stars.
C++
for (int row = 1; row <= 4; row++) {
    for (int col = 1; col <= 4; col++) {
        std::cout << "* ";
    }
    std::cout << std::endl;
}
Sample Program

This program prints pairs of numbers with a star between them, showing how nested loops work together.

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            std::cout << i << "*" << j << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
OutputSuccess
Important Notes

Remember that the inner loop finishes all its cycles before the outer loop moves to the next step.

Too many nested loops can make your program slow and hard to read.

Summary

Nested loops run one loop inside another to handle repeated tasks in rows and columns.

They are useful for grids, tables, and comparing pairs of items.

Keep loops simple and avoid too many levels to stay clear and fast.