Menu
Coddy logo textTech

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:

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

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

The outer loop (x) runs twice, and for each of those times, the inner loop (y) also runs twice — giving us 4 lines of output in total.

In the example above, Console.WriteLine() prints each result on a new line.
If you want to print without moving to a new line, use Console.Write() instead:

Console.Write("Hello ");
Console.Write("World");
// Output: Hello World

Both methods are useful — Console.WriteLine() adds a newline at the end, while Console.Write() keeps the cursor on the same 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:

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

Cheat sheet

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

Example of nested loops:

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

// Output:
// 0 0
// 0 1
// 1 0
// 1 1

The outer loop runs twice, and for each iteration, the inner loop runs twice completely.

Printing output:
Console.WriteLine() prints a value and moves to a new line.
Console.Write() prints a value without moving to a new line, so the next output continues on the same line.

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