Menu
CoddyTech

Nested Loop

Part of the Fundamentals section of Coddy's C# journey. Lesson 46 of 69.

A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop.

A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.

Example of a nested loop:

int rows = 2;
int cols = 2;
for (int x = 0; x < rows; x++) {
	for (int y = 0; y < cols; y++) {
		Console.WriteLine(x + " " + y);
	}
}

// This will output:
// 0 0
// 0 1
// 1 0
// 1 1

The outer loop (x) runs rows times, and for each of those times, the inner loop (y) runs cols times, meaning the inner loop's body executes a total of 2 × 2 = 4 times. Each loop has its own counter: y starts again from 0 every time the outer loop runs, while rows and cols stay the same and only tell the loops when to stop.

You may also need Console.Write() when working with nested loops. Unlike Console.WriteLine(), which prints text and moves to a new line, Console.Write() prints text without adding a newline at the end. This lets you build up output on the same line:

for (int y = 0; y < 4; y++) {
	Console.Write("* ");
}
Console.WriteLine();

// This will output:
// * * * * 

Here, Console.Write() keeps printing on the same line, and Console.WriteLine() at the end moves to the next line.

challenge icon

Challenge

Beginner

Write a program that prints a rectangle of asterisks (*) with a given width and height.

Input: Two integers: width and height

For example:

If width = 5 and height = 3, the output should be:

*****
*****
*****

If width = 4 and height = 6, the output should be:

****
****
****
****
****
****

Use a new counter for each loop (for example i for the rows and j for the stars in a row) and compare it with height or width. Don't change height and width themselves: every row needs width again.

Try it yourself

using System;

public class Program {
    public static void Main(string[] args) {
        int width = int.Parse(Console.ReadLine());
        int height = int.Parse(Console.ReadLine());
        // Write your code below

    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online C# compiler