Loops: for, while, foreach
Loops: for, while, foreach
Loops repeat a block of code while a condition holds.
for — when you know how many times
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
The three parts are: initialiser (int i = 1), condition (i <= 5) and step (i++).
while — as long as the condition is true
int n = 12345;
int sum = 0;
while (n > 0)
{
sum += n % 10; // last digit
n /= 10; // drop it
}
Console.WriteLine(sum); // 15
foreach — for every element
int[] data = { 4, 8, 15 };
foreach (int x in data)
{
Console.WriteLine(x);
}
The most common mistakes
- Infinite loop: forgetting to change the variable inside a
while. - Off-by-one errors:
i < nandi <= nrepeat a different number of times. - Modifying the collection inside a
foreach— it throws.
Practice
Solve "Sum of digits" (a while loop with % 10 and / 10) and "Count the vowels" (foreach over the characters of a string).