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 repeatwhile— when you repeat until something changesdo-while— like while, but guaranteed to run at least onceforeach— when you want to visit every item in an array or collection
for and while Loops
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
Nested Loops — Loops Inside Loops
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.