C# Loops
Loops repeat a block of code while a condition is true, so you can do the same task many times with little code.
The while Loop
Example
csharp
int bottles = 3;
while (bottles > 0)
{
Console.WriteLine($"{bottles} bottles left");
bottles--;
}
Console.WriteLine("All sold!");Output
3 bottles left 2 bottles left 1 bottles left All sold!
The do...while Loop
The body runs once before the condition is checked:
Example
csharp
string answer;
do
{
Console.Write("Type yes to continue: ");
answer = Console.ReadLine();
} while (answer != "yes");
Console.WriteLine("Thank you!");Output
Type yes to continue: no Type yes to continue: yes Thank you!
The for Loop
Example
text
for (start; condition; step)
{
// code to repeat
}Example
csharp
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"12 x {i} = {12 * i}");
}Output
12 x 1 = 12 12 x 2 = 24 12 x 3 = 36 12 x 4 = 48 12 x 5 = 60
The foreach Loop
foreach goes through every item of an array or list:
Example
csharp
string[] subjects = { "English", "Urdu", "Maths", "Computer" };
foreach (string subject in subjects)
{
Console.WriteLine(subject);
}Output
English Urdu Maths Computer
You cannot change the loop variable inside a foreach. If you need to change items, use a for loop with an index.
break and continue
| Statement | What it does |
|---|---|
break | Leaves the loop immediately |
continue | Skips to the next round |
Example
csharp
for (int n = 1; n <= 10; n++)
{
if (n == 3)
{
continue; // skip 3
}
if (n == 6)
{
break; // stop at 6
}
Console.Write(n + " ");
}
Console.WriteLine();Output
1 2 4 5
Building a Total
Example
csharp
int[] dailySales = { 4500, 3200, 5100, 2800, 6000 };
int total = 0;
foreach (int sale in dailySales)
{
total += sale;
}
Console.WriteLine($"Weekly total: Rs {total}");Output
Weekly total: Rs 21600
Printing a Pattern
Loops are often used to print patterns. Here each round prints one more star:
Example
csharp
for (int row = 1; row <= 3; row++)
{
Console.WriteLine(new string('*', row));
}Output
* ** ***
Here new string('*', row) builds a string with row stars, so no inner loop is needed. Look for helpers like this before writing nested loops.
Exercise
Exercise
Which loop is made for going through each item in a collection?
