🔁 Nested Loops in C#
In C#, a nested loop means placing one loop inside another. This is a powerful structure used to handle multi-dimensional data, patterns, grids, and more.
📘 What is a Nested Loop?
A nested loop is when a loop runs inside another loop. The inner loop completes all its iterations for each iteration of the outer loop. Nested loops are commonly used to create patterns or work with matrices and tables.
💡 Common Use Cases
- Printing patterns and shapes (stars, pyramids)
- Working with 2D arrays or matrices
- Nested iterations for comparisons and sorting
📄 C# Example: Nested For Loop
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 5; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
📝 Sample Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
🔍 Explanation
- The
outer loop
runs 3 times (rows). - The
inner loop
runs 5 times for each outer iteration, printing stars horizontally. Console.WriteLine()
moves to the next line after each inner loop finishes.- The result is a 3x5 star grid.
You can nest any type of loop in C#: for
, while
, or do-while
. The key idea is: every time the outer loop executes once, the inner loop executes fully.
Post a Comment