5. Loops
Loops repeat code. for is used when you know how many times to repeat: it has an initialiser, a condition and an update (for (int i = 0; i < n; i++)). while repeats as long as a condition is true and checks it before each pass, so it may run zero times. do/while checks the condition after the body, so it always runs at least once. foreach walks through every item of a collection (an array, List<T>, string, dictionary, or anything that implements IEnumerable) without needing an index.
break exits the nearest loop immediately and continue skips to the next iteration. Loops can be nested: the inner loop runs completely for every pass of the outer loop, which is how you process tables and 2D arrays. A loop whose condition never becomes false is an infinite loop (while (true)); it is only correct when something inside ends it with break, return or an exception.
Choose the loop by what you know: for when you need the index or a fixed count, foreach to visit every item, while when you repeat until something happens (such as valid input), and do/while when the body must run at least once (such as showing a menu).
Key points to remember
- A for loop's variable (i) exists only inside the loop. Loops often run from 0 to Length - 1, so use < and not <= with Length.
- Common mistake: an off-by-one error (i <= array.Length causes IndexOutOfRangeException).
- Common mistake: forgetting to change the loop variable in a while loop, which creates an infinite loop.
- You cannot add or remove items from a collection while a foreach is walking it (InvalidOperationException). Loop over a copy (ToList()) or use RemoveAll.
- The foreach variable is read-only. To change array items, use a for loop and the index.
- Enumerable.Range(start, count) produces a sequence of numbers for use with foreach or LINQ.
- For very long loops over large data, prefer LINQ or built-in methods (Sum, Max, Contains) when they say the same thing more clearly.
Example 1: for and foreach
for (int i = 1; i <= 3; i++)
Console.WriteLine("Count " + i);
string[] fruits = { "apple", "pear" };
foreach (var f in fruits)
Console.WriteLine(f);
Show output
OutputCount 1 Count 2 Count 3 apple pear
Example 2: for loop variations
for (int i = 10; i >= 0; i -= 5) // counting down in steps
Console.WriteLine(i);
for (int i = 0, j = 10; i < j; i += 4, j -= 4) // two variables
Console.WriteLine($"{i} {j}");
string[] names = { "Ann", "Ben" };
for (int i = 0; i < names.Length; i++) // index needed
Console.WriteLine($"{i}: {names[i]}");
Show output
Output10 5 0 0 10 4 6 0: Ann 1: Ben
Example 3: while and do / while
int n = 3;
while (n > 0)
{
Console.Write(n + " ");
n--;
}
Console.WriteLine();
int k = 10;
do
{
Console.WriteLine("Runs once, k = " + k);
k++;
} while (k < 5);
Show output
Output3 2 1 Runs once, k = 10
Example 4: while with break and continue
int n = 0;
while (true)
{
n++;
if (n == 2) continue;
if (n > 4) break;
Console.WriteLine(n);
}
Show output
Output1 3 4
Example 5: Nested loops: multiplication table
for (int r = 1; r <= 3; r++)
{
for (int c = 1; c <= 3; c++)
Console.Write($"{r * c,4}"); // ,4 right-aligns in a width of 4
Console.WriteLine();
}
Show output
Output1 2 3 2 4 6 3 6 9
Example 6: Accumulating: sum, factorial and counting
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i;
Console.WriteLine(sum);
long factorial = 1;
for (int i = 2; i <= 5; i++) factorial *= i;
Console.WriteLine(factorial);
int evens = 0;
foreach (int number in new[] { 3, 8, 12, 7, 20 })
if (number % 2 == 0) evens++;
Console.WriteLine(evens);
Show output
Output5050 120 3
Example 7: foreach over strings, ranges and dictionaries
foreach (char ch in "abc")
Console.Write(ch + "-");
Console.WriteLine();
foreach (int i in Enumerable.Range(1, 3))
Console.Write(i + " ");
Console.WriteLine();
var ages = new Dictionary<string, int> { ["Ann"] = 30, ["Ben"] = 25 };
foreach (var pair in ages)
Console.WriteLine($"{pair.Key} = {pair.Value}");
Show output
Outputa-b-c- 1 2 3 Ann = 30 Ben = 25
Example 8: Searching and stopping early
int[] data = { 4, 9, 15, 22, 31 };
int target = 15;
int foundAt = -1;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == target)
{
foundAt = i;
break; // no need to look further
}
}
Console.WriteLine(foundAt);
for (int i = 2; i <= 20; i++) // print primes up to 20
{
bool prime = true;
for (int d = 2; d * d <= i; d++)
if (i % d == 0) { prime = false; break; }
if (prime) Console.Write(i + " ");
}
Show output
Output2 2 3 5 7 11 13 17 19
Example 9: Validating input with a loop
int number;
Console.Write("Enter a number from 1 to 10: ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 10)
{
Console.Write("Invalid. Try again: ");
}
Console.WriteLine("You entered " + number);
Show output
OutputEnter a number from 1 to 10: abc Invalid. Try again: 42 Invalid. Try again: 7 You entered 7