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) runs twice — meaning the inner loop's body executes a total of 4 times.

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:

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

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