Loops
Prerequisites: Switch statements & expressions
Syntax
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
int i = 0;
while (i < 5) {
Console.WriteLine(i);
i++;
}
int[] nums = { 10, 20, 30 };
foreach (int n in nums) {
Console.WriteLine(n);
}
Example
for (int i = 1; i <= 3; i++) {
Console.WriteLine($"Count: {i}");
}
Expected output
Count: 1
Count: 2
Count: 3
foreach is C#'s equivalent of Java's enhanced for loop — the
everyday choice whenever you just need each element, with no index.
Practice
Print the numbers 1 through 5 using a for loop.
Show solution
for (int i = 1; i <= 5; i++) {
Console.WriteLine(i);
}