Loops: for, while, do-while, foreach
Repeat work without copying code. See exactly how a loop runs, step by step, and learn which loop to choose.
WriteLine lines would be silly. A loop repeats a block of code while a condition is true. Each repetition is called an iteration.
The for loop
for when you know how many times to repeat. Its header has three parts separated by semicolons: start; condition; update.
for (int i = 1; i <= 5; i++){ Console.Write(i + " ");}1 2 3 4 5
The while loop
while when you don’t know in advance how many times to repeat. You only know when to stop.
int money = 1000;int years = 0; while (money < 2000){ money += money * 10 / 100; // 10% interest years++;}Console.WriteLine($"Doubled after {years} years: {money}");Doubled after 8 years: 2142
The do-while loop
do...while checks the condition after the body, so the body always runs at least once. Perfect for “ask until the input is valid”.
int age;do{ Console.Write("Enter age (1-120): ");} while (!int.TryParse(Console.ReadLine(), out age) || age < 1 || age > 120); Console.WriteLine($"Thanks! Age = {age}");Enter age (1-120): abc Enter age (1-120): 200 Enter age (1-120): 24 Thanks! Age = 24
The foreach loop
foreach visits every item of a collection (an array, a list, the characters of a string) without any index counting. It is the simplest and safest loop for reading items.
string[] members = { "Column", "Beam", "Brace" };foreach (string m in members){ Console.WriteLine($"Checking {m}");} foreach (char ch in "C#") Console.WriteLine(ch);Checking Column Checking Beam Checking Brace C #
Which loop should I use?
| Loop | Use when | Runs at least once? |
|---|---|---|
for | ||
while | ||
do-while | ||
foreach |
Counting down and stepping
for (int i = 10; i >= 0; i -= 2) Console.Write(i + " ");10 8 6 4 2 0
Show the solution
Console.Write("Number: ");int n = int.Parse(Console.ReadLine() ?? "0"); for (int i = 1; i <= 10; i++){ Console.WriteLine($"{n} x {i} = {n * i}");}Number: 7 7 x 1 = 7 7 x 2 = 14 ... 7 x 10 = 70
Show a hint
Show the solution
int number = 40512;int digits = 0;while (number > 0){ number /= 10; digits++;}Console.WriteLine(digits);5
Remember
for (start; condition; update): check → body → update, repeated.whilerepeats while a condition is true;do-whileruns at least once.foreachreads every item in a collection without an index.Always make sure the condition can become false, or the loop never ends.