Loops allow your C# programs to repeat tasks efficiently — without writing the same code over and over again. Whether you’re counting numbers, processing lists, or repeating user input prompts, loops are a vital tool in every C# developer’s toolkit.
Here, we’ll explore the four main loop types in C# — for
, while
, do-while
, and foreach
— with clear examples and tips on when to use each one.
🎯 Why Use Loops?
Loops help you:
- Repeat a block of code a set number of times
- Iterate over items in arrays or collections
- Automate repetitive tasks like input, calculations, or output
🔁 The for
Loop
Use a for
loop when you know exactly how many times you want to repeat something.
🔹 Syntax:
for (initialization; condition; update)
{
// Code to repeat
}
🔸 Example:
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Count: " + i);
}
✅ Use
for
when working with counters or index-based operations.
🔄 The while
Loop
A while
loop checks the condition before each iteration. It repeats as long as the condition is true.
🔹 Syntax:
while (condition)
{
// Code to repeat
}
🔸 Example:
int count = 0;
while (count < 3)
{
Console.WriteLine("Repeating...");
count++;
}
⚠️ Be careful of infinite loops — always make sure the condition can eventually become false.
🔁 The do-while
Loop
A do-while
loop runs the code at least once, then checks the condition.
🔹 Syntax:
do
{
// Code to repeat
}
while (condition);
🔸 Example:
string input;
do
{
Console.Write("Enter your name: ");
input = Console.ReadLine();
}
while (input == "");
✅ Use
do-while
when you want to run the loop body at least once (e.g., menu prompts, user input).
🔁 The foreach
Loop
Use foreach
to loop over items in arrays, lists, or other collections. It’s simple and avoids index errors.
🔹 Syntax:
foreach (var item in collection)
{
// Code using item
}
🔸 Example:
string[] fruits = { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
✅ Use
foreach
when you don’t need to modify the collection or track indexes.
🧪 Quick Challenge: Combine Loops
Try writing a program that:
- Uses a
for
loop to ask the user for 5 numbers - Adds them up in a total
- Then uses a
foreach
loop to print all the numbers back
int[] numbers = new int[5];
for (int i = 0; i < numbers.Length; i++)
{
Console.Write("Enter number " + (i + 1) + ": ");
numbers[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nYou entered:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
🧠 Summary: When to Use Each Loop
Loop Type | Best Used For |
---|---|
for | Fixed repetitions, counting with indexes |
while | Repeat as long as a condition is true |
do-while | Ensure the loop runs at least once |
foreach | Easy iteration over arrays, lists, or collections |
🚀 Need Help?
Want more hands-on practice? Join one of our C# Essentials Workshops or contact us for private coaching at csharptraining.co.uk/contact.