DEV Community

Sabin Sim
Sabin Sim

Posted on

25. C# (Nested Loop)

0. The Real Goal of This Lesson

In a nested loop,
every single outer iteration triggers a full execution of the inner loop.

Core principle:

One outer cycle = one complete inner cycle.

If you misunderstand this:

  • You miscalculate execution counts
  • You underestimate performance cost
  • You struggle with algorithm complexity

This is not about memorizing syntax.

It is about understanding multiplicative execution flow.


1. The 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

Execution Flow — Step by Step

When i = 1

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

Inner loop completes.


When i = 2

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

And so on.


Total executions:

4 outer × 3 inner = 12 executions


Structural Visualization

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

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

Important:

j resets for every new i.

The inner loop starts from its initial state every time.


2. Understanding 4 × 3 Structurally

Mathematically, this is simple.

Structurally, it is clearer:

Outer loop = number of sets
Inner loop = repetitions inside each set

Example:

  • 4 boxes
  • 3 items per box

Total items:

4 × 3 = 12

This is multiplicative repetition.


3. Deeper Nesting — 4 × 3 × 5

Runnable Example

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 Executions?

Outer: 4
Middle: 3
Inner: 5

Total:

4 × 3 × 5 = 60 executions

Each additional level multiplies the total count.


4. Why Performance Becomes a Concern

Each added nested loop increases complexity.

Example:

  • 100 × 100 → 10,000 iterations
  • 1,000 × 1,000 → 1,000,000 iterations

With three nested loops:

  • 100 × 100 × 100 → 1,000,000 iterations

This growth is exponential.

In complexity terms:

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

Nested loops are powerful.

But they scale aggressively.


5. Where Nested Loops Are Used in Practice

Common scenarios:

  • Two-dimensional arrays
  • Coordinate systems
  • Grid processing
  • Table generation
  • Pairwise comparisons
  • Algorithm problems

Whenever combinations of elements are involved, nested loops appear.


6. Observing the Flow in Rider

To fully understand:

  1. Place a breakpoint inside the innermost loop
  2. Use Step Into (F11)
  3. Observe how k completes
  4. Then j increments
  5. Only after j finishes does i increment

Key observation:

The inner loop must fully finish before the outer loop continues.

This is hierarchical execution.


7. The Critical Thinking Habit

When reading nested loops, always ask:

How many total executions occur?

And think in multiplication:

outer_count × inner_count × ...
Enter fullscreen mode Exit fullscreen mode

Never think linearly.

Nested loops are multiplicative by nature.


8. What You Must Understand at This Level

At your current level, you must clearly grasp:

  • Execution count grows by multiplication
  • Inner loop resets every outer iteration
  • More depth means exponential growth
  • Performance impact increases rapidly

These are structural truths.

Not implementation details.


Final Summary

A nested loop executes the entire inner loop for each iteration of the outer loop,
and total execution count increases multiplicatively.

Top comments (0)