What are Nested Loops?
A nested loop is a loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.
Basic Concept
for (outer loop)
{
for (inner loop)
{
// Code executes for each combination
}
}
Simple Example
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
Console.WriteLine($"i = {i}, j = {j}");
}
}
// Output:
// i = 1, j = 1
// i = 1, j = 2
// i = 2, j = 1
// i = 2, j = 2
// i = 3, j = 1
// i = 3, j = 2
How Nested Loops Work
For each iteration of the outer loop, the inner loop runs completely.
for (int row = 1; row <= 2; row++) // Outer: runs 2 times
{
for (int col = 1; col <= 3; col++) // Inner: runs 3 times per outer
{
Console.Write("*");
}
Console.WriteLine(); // New line after inner loop
}
// Output:
// ***
// ***
Breakdown:
- row=1: col runs 1,2,3 → prints ***
- row=2: col runs 1,2,3 → prints ***
Pattern Printing Examples from Course
Example 1: Increasing Letters (From Practical Test 4)
using System;
namespace Pattern1
{
class Program
{
static void Main(string[] args)
{
char ch = 'A';
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(ch + " ");
}
Console.WriteLine();
ch++;
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
// Output:
// A
// B B
// C C C
// D D D D
// E E E E E
Example 2: Alternating Pattern (From Practical Test 4)
using System;
namespace Pattern2
{
class Program
{
static void Main(string[] args)
{
string sJs = "Js";
string sCss = "CSS";
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
if (j % 2 == 0)
{
Console.Write(sJs + " ");
}
else
{
Console.Write(sCss + " ");
}
}
Console.WriteLine();
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
// Output:
// Js
// Js CSS
// Js CSS Js
// Js CSS Js CSS
// Js CSS Js CSS Js
Example 3: Decreasing Numbers (From Practical Test 4)
using System;
namespace Pattern3
{
class Program
{
static void Main(string[] args)
{
for (int i = 5; i >= 1; i--)
{
for (int j = 0; j < i; j++)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}
// Output:
// 5 5 5 5 5
// 4 4 4 4
// 3 3 3
// 2 2
// 1
More Pattern Examples from Worksheets
Pattern 1: Increasing Numbers (From Worksheet 4)
int iA = 1;
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j < i; j++)
{
Console.Write(iA + " ");
iA++;
}
Console.WriteLine();
}
// Output:
// (nothing - i=0)
// 1
// 2 3
// 4 5 6
// 7 8 9 10
Pattern 2: C and # Alternating (From Worksheet 4)
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <= i; j++)
{
if (j % 2 == 0)
{
Console.Write("C ");
}
else
{
Console.Write("# ");
}
}
Console.WriteLine();
}
// Output:
// C
// C #
// C # C
// C # C #
// C # C # C
Pattern 3: Decreasing Letters (From Worksheet 4)
char ch = 'A';
for (int i = 5; i >= 1; i--)
{
for (int j = 0; j < i; j++)
{
Console.Write(ch + " ");
}
Console.WriteLine();
ch++;
}
// Output:
// A A A A A
// B B B B
// C C C
// D D
// E
Common Nested Loop Patterns
Pattern: Rectangle
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// Output:
// * * * * *
// * * * * *
// * * * * *
Pattern: Right Triangle
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
Pattern: Inverted Triangle
for (int i = 5; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// Output:
// * * * * *
// * * * *
// * * *
// * *
// *
Pattern: Number Pyramid
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
// Output:
// 1
// 1 2
// 1 2 3
// 1 2 3 4
// 1 2 3 4 5
Pattern: Multiplication Table
Console.WriteLine("Multiplication Table (1-10)");
Console.WriteLine("============================");
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
Console.Write($"{i * j,4}"); // 4-character width
}
Console.WriteLine();
}
Practical Applications
Application 1: Grid/Matrix Processing
int[,] iMatrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Console.WriteLine("Matrix:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write(iMatrix[i, j] + " ");
}
Console.WriteLine();
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9
Application 2: Combinations
string[] sColors = { "Red", "Green", "Blue" };
string[] sSizes = { "Small", "Medium", "Large" };
Console.WriteLine("All Combinations:");
for (int i = 0; i < sColors.Length; i++)
{
for (int j = 0; j < sSizes.Length; j++)
{
Console.WriteLine($"{sSizes[j]} {sColors[i]}");
}
}
// Output:
// Small Red
// Medium Red
// Large Red
// Small Green
// Medium Green
// Large Green
// Small Blue
// Medium Blue
// Large Blue
Application 3: Calendar Grid
Console.WriteLine("Calendar Week View");
Console.WriteLine("Sun Mon Tue Wed Thu Fri Sat");
int iDay = 1;
for (int week = 0; week < 5; week++)
{
for (int day = 0; day < 7; day++)
{
if (iDay <= 31)
{
Console.Write($"{iDay,3} ");
iDay++;
}
}
Console.WriteLine();
}
Three-Level Nested Loops
You can nest loops more than two levels deep (though it gets complex):
for (int i = 1; i <= 2; i++)
{
for (int j = 1; j <= 2; j++)
{
for (int k = 1; k <= 2; k++)
{
Console.WriteLine($"i={i}, j={j}, k={k}");
}
}
}
// Output:
// i=1, j=1, k=1
// i=1, j=1, k=2
// i=1, j=2, k=1
// i=1, j=2, k=2
// i=2, j=1, k=1
// i=2, j=1, k=2
// i=2, j=2, k=1
// i=2, j=2, k=2
Break and Continue in Nested Loops
Break: Exits Only Inner Loop
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (j == 2)
{
break; // Only exits inner loop
}
Console.Write($"({i},{j}) ");
}
Console.WriteLine();
}
// Output:
// (1,1)
// (2,1)
// (3,1)
Continue: Skips Inner Loop Iteration
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (j == 2)
{
continue; // Skip j=2
}
Console.Write($"({i},{j}) ");
}
Console.WriteLine();
}
// Output:
// (1,1) (1,3)
// (2,1) (2,3)
// (3,1) (3,3)
Practice Exercises
Exercise 1: Square Pattern
Create a 7x7 square of asterisks.
Exercise 2: Number Square
Create a pattern:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Exercise 3: Pyramid
Create a centered pyramid:
*
***
*****
*******
*********
Exercise 4: Checkerboard
Create a checkerboard pattern with X and O:
X O X O X
O X O X O
X O X O X
O X O X O
X O X O X
Exercise 5: Diamond
Create a diamond shape using asterisks.
Performance Considerations
Nested loops can be slow with large datasets:
// This is O(n²) - slow for large n!
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 1000; j++)
{
// 1,000,000 iterations!
}
}
Tips: - Avoid unnecessary nested loops - Break early when possible - Consider if there's a better algorithm
Common Mistakes to Avoid
❌ Using same variable name:
for (int i = 0; i < 5; i++)
{
for (int i = 0; i < 3; i++) // WRONG! Same variable name
{
Console.Write(i);
}
}
✅ Correct:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++) // Different variable
{
Console.Write(j);
}
}
❌ Forgetting Console.WriteLine():
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("* ");
}
// Missing WriteLine! All on one line
}
// Output: * * * * * * * * *
✅ Correct:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("* ");
}
Console.WriteLine(); // New line after each row
}
Key Takeaways
✅ Inner loop completes fully for each outer loop iteration ✅ Perfect for 2D patterns, grids, and tables ✅ Use different variable names (i, j, k) ✅ Remember to use WriteLine() after inner loop for new line ✅ Break only exits the innermost loop ✅ Can nest more than 2 levels (but avoid complexity) ✅ Watch performance with large datasets
Next Topic: C# Methods (Functions)