Loops and Iteration: for, while, and foreach

Repeating actions in C#

Posted by Rodrigo Castro on October 26, 2024

Loops let your program do something over and over: great for processing lists or repeating tasks.

🔁 for Loop

Count a known number of times:

1
2
3
4
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

🔄 while Loop

Repeat while something is true:

1
2
3
4
5
6
int n = 3;
while (n > 0)
{
    Console.WriteLine(n);
    n--;
}

🔁 foreach Loop

Go through every item in a collection:

1
2
3
4
5
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

💡 When to Use Each

  • for: When you know how many times to loop.
  • while: When you want to loop until a condition is false.
  • foreach: When looping through a collection (array, list, etc.).

📝 Try It!

Print all even numbers from 2 to 10:

1
2
for (int i = 2; i <= 10; i += 2)
    Console.WriteLine(i);

Next: Using break, continue, and return in loops!