DEV Community

Sabin Sim
Sabin Sim

Posted on

32. C# (Nested Loop)

0. The Essence of Nested Loops

Every time the outer loop runs once,
the inner loop runs completely from start to finish.

Core rule:

One outer iteration = one full execution set of the inner loop

If this mental model is not clear, nested loops quickly become confusing.


1. Basic Example — 4 × 3

Full Runnable Code

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 4; i++)
        {
            for (int j = 1; j <= 3; j++)
            {
                Console.WriteLine($"Outer: {i}, Inner: {j}");
            }
        }

        Console.WriteLine("Finished.");
        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution Flow

When i = 1

  • j = 1 → print
  • j = 2 → print
  • j = 3 → print

Inner loop ends.


When i = 2

  • j = 1 → print
  • j = 2 → print
  • j = 3 → print

Total Execution Count

Outer loop runs 4 times.
Inner loop runs 3 times per outer iteration.

So the total number of executions is:

4 × 3 = 12
Enter fullscreen mode Exit fullscreen mode

Structural Visualization

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

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

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

i=4
  j=1
  j=2
  j=3
Enter fullscreen mode Exit fullscreen mode

Notice an important detail:

The inner loop variable j is reinitialized every time the outer loop starts again.


2. Intuitive Way to Understand 4 × 3

Instead of thinking mathematically, think structurally.

The outer loop represents:

the number of sets

The inner loop represents:

the number of items inside each set

Example analogy:

  • 4 boxes
  • each box contains 3 objects

Total objects:

4 × 3 = 12
Enter fullscreen mode Exit fullscreen mode

This is exactly how nested loops behave.


3. Deeper Nesting — 4 × 3 × 5

Example Code

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 4; i++)
        {
            for (int j = 1; j <= 3; j++)
            {
                for (int k = 1; k <= 5; k++)
                {
                    Console.WriteLine($"i:{i}, j:{j}, k:{k}");
                }
            }
        }

        Console.WriteLine("Finished.");
        Console.ReadKey();
    }
}
Enter fullscreen mode Exit fullscreen mode

How Many Times Does It Execute?

Outer loop:

4
Enter fullscreen mode Exit fullscreen mode

Middle loop:

3
Enter fullscreen mode Exit fullscreen mode

Inner loop:

5
Enter fullscreen mode Exit fullscreen mode

Total executions:

4 × 3 × 5 = 60
Enter fullscreen mode Exit fullscreen mode

Why Nested Loops Affect Performance

Every additional nesting level multiplies execution cost.

Growth pattern:

O(n)
O(n²)
O(n³)
Enter fullscreen mode Exit fullscreen mode

Example:

100 × 100 = 10,000 operations
1000 × 1000 = 1,000,000 operations
Enter fullscreen mode Exit fullscreen mode

When the dataset grows large, nested loops can quickly become a performance bottleneck.

This is why developers must use them carefully.


4. Where Nested Loops Are Used in Practice

Common scenarios include:

  • iterating through 2D arrays
  • coordinate calculations
  • generating tables or grids
  • comparing two datasets
  • algorithmic problems

Many classic algorithms rely heavily on nested loops.


5. Understanding the Flow Using a Debugger

A very effective way to learn this is debugging.

Steps:

  1. Place a breakpoint on the innermost Console.WriteLine.
  2. Use Step Into (F11) repeatedly.
  3. Observe how i, j, and k change.

You will notice:

The inner loop finishes completely before the outer loop continues.

Seeing this once in a debugger makes the structure very clear.


6. The Most Important Mental Model

Whenever you see nested loops, think like this:

The inner loop runs completely inside a single iteration of the outer loop.

If you misunderstand this, algorithmic reasoning becomes very difficult.


7. Key Points to Remember

At your current stage, you should clearly understand:

  • Execution count follows a multiplication pattern
  • The inner loop is reinitialized every time
  • More nesting increases execution exponentially
  • Performance is directly affected

Final Summary

A nested loop is a structure where one loop executes completely inside another loop, and the total execution count grows through multiplication.

Top comments (0)