Lesson 56 min read

Loops

Do it once, do it a thousand times — automatically

Why Loops?

Imagine you need to print "Hello" 100 times. You could write 100 Console.WriteLine statements... or you could write a loop and let the computer do the boring stuff. Loops are your code's repeat button.

C# has four types of loops, each with its sweet spot:

  • for — when you know exactly how many times to repeat
  • while — when you repeat until something changes
  • do-while — like while, but guaranteed to run at least once
  • foreach — when you want to visit every item in an array or collection

for and while Loops

// for loop — "do this N times"
// (start; keep going while; after each loop)
Console.WriteLine("Countdown:");
for (int i = 5; i >= 1; i--)
{
Console.Write($"{i}... ");
}
Console.WriteLine("Liftoff!");
// while loop — "keep going until this is false"
int fuel = 100;
Console.WriteLine("\nBurning fuel:");
while (fuel > 0)
{
fuel -= 30;
Console.WriteLine($" Fuel remaining: {Math.Max(fuel, 0)}%");
}
// do-while — runs AT LEAST once
int attempts = 0;
do
{
attempts++;
Console.WriteLine($"Attempt #{attempts}");
} while (attempts < 3);
Output
Countdown:
5... 4... 3... 2... 1... Liftoff!

Burning fuel:
  Fuel remaining: 70%
  Fuel remaining: 40%
  Fuel remaining: 10%
  Fuel remaining: 0%
Attempt #1
Attempt #2
Attempt #3

foreach — The Collection Whisperer

foreach is the friendliest loop. It says "give me each item in this collection, one at a time." You don't need to track an index or worry about going out of bounds. It just works.

Use foreach whenever you're iterating over arrays, lists, strings (yes, strings are collections of characters!), or any other collection.

foreach, break, and continue

// foreach with an array
string[] heroes = { "Spider-Man", "Batman", "Wonder Woman", "Iron Man" };
foreach (string hero in heroes)
{
Console.WriteLine($" Hero: {hero}");
}
// foreach with a string (each char!)
string word = "C#";
foreach (char c in word)
{
Console.Write($"[{c}]");
}
Console.WriteLine();
// break — emergency exit
Console.WriteLine("\nSearching for Batman:");
foreach (string hero in heroes)
{
if (hero == "Batman")
{
Console.WriteLine(" Found him!");
break; // stop the loop right now
}
Console.WriteLine($" Not {hero}...");
}
// continue — skip this one, keep going
Console.WriteLine("\nOdd numbers only:");
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
continue; // skip even numbers
Console.Write($"{i} ");
}
Console.WriteLine();
Output
  Hero: Spider-Man
  Hero: Batman
  Hero: Wonder Woman
  Hero: Iron Man
[C][#]

Searching for Batman:
  Not Spider-Man...
  Found him!

Odd numbers only:
1 3 5 7 9 

Nested Loops — Loops Inside Loops

// Print a multiplication table
Console.WriteLine("Multiplication Table (1-4):");
for (int row = 1; row <= 4; row++)
{
for (int col = 1; col <= 4; col++)
{
Console.Write($"{row * col,4}"); // ,4 pads to 4 chars
}
Console.WriteLine();
}
// Build a triangle
Console.WriteLine("\nTriangle:");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(new string('*', i));
}
Output
Multiplication Table (1-4):
   1   2   3   4
   2   4   6   8
   3   6   9  12
   4   8  12  16

Triangle:
*
**
***
****
*****
Note: ⚠️ Infinite loop alert! If your while/for condition never becomes false, your program will run forever (or until you force-quit it). Always make sure something inside the loop moves you closer to the exit condition. Common trap: forgetting to increment your counter.

Quick check

How many times does a do-while loop always run at minimum?
ConditionalsArrays & Lists