Nested Loops — Designing the City Grid
20 XPMedium
Ctrl+Enter RunCtrl+S Save
A real city isn't a single line of buildings — it's a grid. Rows of streets crossing columns of avenues, with a city block at every intersection. To build a grid, you need a loop inside a loop — a nested loop.
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
Console.Write($"Block [{row},{col}] ");
}
Console.WriteLine(); // new line after each row
}
Console.Write prints without a newline; Console.WriteLine() after the inner loop moves to the next row
The break statement — emergency stop! It exits the nearest enclosing loop immediately:
for (int i = 0; i < 10; i++)
{
if (i == 3)
break; // exits the loop when i reaches 3
Console.WriteLine(i);
}
// Prints: 0, 1, 2
⚠️ In nested loops, break only exits the innermost loop. The outer loop keeps running! If you need to break out of both, use a boolean flag or restructure with a method and return.
The continue statement — skip this block and move on. It jumps to the next iteration of the nearest enclosing loop:
for (int i = 0; i < 5; i++)
{
if (i == 2)
continue; // skip block 2
Console.WriteLine($"Building block {i}");
}
// Prints: 0, 1, 3, 4 — block 2 is skipped!
Quick reference:
break — exits the loop entirely ("tear down the construction site")
continue — skips the current iteration ("skip this block, build the next")
return — exits the entire method, not just the loop
C# does not have labeled breaks like Java — use a flag variable or method extraction instead
💡 Performance note: Nested loops multiply iterations. A 100×100 grid means 10,000 iterations. A 1000×1000 grid hits 1,000,000. Always be aware of the total work your nested loops are doing — a city planner must think about scale!
📋 Instructions
**Mission: Design a 3×3 city grid!**
The mayor wants a grid layout for the new district. Write a program that:
1. Uses **nested for loops** (outer for rows 0–2, inner for columns 0–2)
2. Prints `Block [row,col] ` (with a trailing space) using `Console.Write` for each block
3. After each row's inner loop completes, prints a newline using `Console.WriteLine()`
4. Tracks the total number of blocks built
5. After both loops finish, prints `City grid complete! 9 blocks built`
Your grid should look exactly like a 3×3 matrix of blocks!
Use `int totalBlocks = 0;` before the loops. Outer loop: `for (int row = 0; row < 3; row++)`. Inner loop: `for (int col = 0; col < 3; col++)`. Inside the inner loop, use `Console.Write($"Block [{row},{col}] ");` and `totalBlocks++`. After the inner loop (but inside the outer), use `Console.WriteLine();`. After both loops, print the completion message.