0
0
C Sharp (C#)programming~5 mins

Nested loop execution in C Sharp (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 two lists.
When you want to create a multiplication table.
When you process rows and columns in a spreadsheet.
When you want to compare elements inside a matrix.
Syntax
C Sharp (C#)
for (int i = 0; i < outerLimit; i++) {
    for (int j = 0; j < innerLimit; j++) {
        // code to repeat
    }
}

The outer loop runs first, then the inner loop runs completely for each outer loop step.

Use different variable names for each loop to avoid confusion.

Examples
This prints pairs of i and j values, showing how inner loop runs fully for each i.
C Sharp (C#)
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        Console.WriteLine($"i={i}, j={j}");
    }
}
This prints 2 rows of 3 stars each, like a small rectangle.
C Sharp (C#)
for (int row = 0; row < 2; row++) {
    for (int col = 0; col < 3; col++) {
        Console.Write("*");
    }
    Console.WriteLine();
}
Sample Program

This program prints a 3x3 multiplication table. The outer loop controls rows, the inner loop controls columns.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                Console.Write($"{i}x{j}={i*j} ");
            }
            Console.WriteLine();
        }
    }
}
OutputSuccess
Important Notes

Nested loops can slow down your program if they run many times, so use them carefully.

Indent your code inside loops to keep it clear which code belongs to which loop.

Summary

Nested loops run one loop inside another to repeat actions multiple times.

The inner loop finishes all its steps for each step of the outer loop.

They are useful for working with tables, grids, or pairs of items.