100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

Nested Loops in C++

See how placing one loop inside another lets you process grids and patterns in C++, with a full trace of outer × inner iteration counts.

LoopsBeginner6 min readJul 7, 2026
Analogies

1. Intro

A nested loop is simply a loop written inside the body of another loop. The outer loop controls how many times the entire inner loop runs, and the inner loop runs to completion for every single iteration of the outer loop. Nested loops are the standard tool for working with two-dimensional data, such as grids, matrices, and printed patterns like triangles or number tables.

🏏

Cricket analogy: Printing a full tournament's over-by-over scoresheet needs an outer loop for each match and an inner loop for each over within that match — exactly the nested-loop structure used for grids like a Duckworth-Lewis table.

2. Syntax

cpp
for (int i = 0; i < outerLimit; i++) {
    for (int j = 0; j < innerLimit; j++) {
        // inner loop body
    }
}

3. Explanation

Any loop type (for, while, do-while) can be nested inside any other loop type. The total number of times the innermost body executes is the product of the outer loop's iteration count and the inner loop's iteration count (outerLimit x innerLimit for two simple counted loops). Each time the outer loop advances by one iteration, the inner loop's counter is reset and the inner loop runs through its full range again from the start. This is a common exam trap: students forget that the inner loop restarts completely on every pass of the outer loop, rather than continuing from where it left off.

🏏

Cricket analogy: Every one of a bowler's 10 overs (outer) runs a fresh set of 6 balls (inner) — the ball counter resets to 1 at the start of each new over rather than continuing from the last over's count, a common scoring mix-up mirroring the nested-loop reset trap.

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 2; j++) {
            cout << "i=" << i << " j=" << j << "  ";
        }
        cout << endl;
    }
    return 0;
}

5. Output

text
i=1 j=1  i=1 j=2  
i=2 j=1  i=2 j=2  
i=3 j=1  i=3 j=2  

6. Key Takeaways

  • A nested loop is a loop placed inside the body of another loop.
  • The inner loop fully restarts and runs to completion for every single iteration of the outer loop.
  • Total inner-body executions equal outer iterations multiplied by inner iterations (e.g. 3 x 2 = 6 above).
  • Nested loops are the standard way to process 2D structures like grids, matrices, and printed patterns.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#NestedLoopsInC#Nested#Loops#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep