Loops: for, foreach, while and do-while
Why Loops?
A loop repeats code. Without loops, printing the numbers 1 to 100 would take 100 lines.
for Loop: When You Know How Many Times
csharp
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Number {i}");
}
| Part | Meaning |
|---|---|
int i = 1 | Start: runs once |
i <= 5 | Condition: checked before each round |
i++ | Step: runs after each round |
foreach: Go Through Every Item
csharp
string[] cities = { "Delhi", "Paris", "Tokyo" };
foreach (string city in cities)
{
Console.WriteLine(city);
}
foreach is read-only: You cannot change the collection itself inside a
foreach (for example add or remove items). Use a for loop when you need the index.
while: Repeat While a Condition is True
csharp
int count = 3;
while (count > 0)
{
Console.WriteLine(count);
count--;
}
Console.WriteLine("Liftoff!");
do-while: Run At Least Once
csharp
string? answer;
do
{
Console.Write("Type 'yes' to continue: ");
answer = Console.ReadLine();
}
while (answer != "yes");
break and continue
csharp
for (int i = 1; i <= 10; i++)
{
if (i == 3) continue; // skip 3
if (i == 6) break; // stop the loop at 6
Console.WriteLine(i); // 1 2 4 5
}
Nested Loops: A Multiplication Table
csharp
for (int row = 1; row <= 3; row++)
{
for (int col = 1; col <= 3; col++)
{
Console.Write($"{row * col,4}");
}
Console.WriteLine();
}
Result
Each row prints three numbers: 1 2 3, then 2 4 6, then 3 6 9, lined up in columns.
Common Patterns
csharp
int[] numbers = { 4, 8, 15, 16, 23, 42 };
// sum
int sum = 0;
foreach (int n in numbers) sum += n;
// maximum
int max = numbers[0];
foreach (int n in numbers)
if (n > max) max = n;
// search
bool found = false;
foreach (int n in numbers)
{
if (n == 15) { found = true; break; }
}
Infinite loops: If the condition never becomes false, the loop never ends. Make sure something inside the loop changes the condition. Press Ctrl + C in the terminal to stop it.
| Loop | Use when |
|---|---|
for | You know the count or need the index |
foreach | You want every item of a collection |
while | You repeat until something happens |
do-while | You must run the body at least once |
Conclusion
Choose for for counting, foreach for collections, while for 'until' logic and use break and continue to control the flow.
Quick Summary: for = count, foreach = each item, while = until, do-while = at least once.

