Loops in C# – For, While, and Do While with Examples
In C#, loops are used to execute a block of code repeatedly until a specified condition is met. They are a fundamental part of programming for automating repetitive tasks.
for loop
while loop
do-while loop
(Bonus: foreach loop – usually used with arrays or collections)
Example
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Number: " + i);
}
int i = 1;
while (i <= 5)
{
Console.WriteLine("Number: " + i);
i++;
}
int i = 6;
do
{
Console.WriteLine("Number: " + i);
i++;
}
while (i <= 5);
string[] fruits = { "Apple", "Banana", "Mango" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Summary
Best for iterating through arrays/collections.
Automatically picks each item.
for ? Condition ? Execute ? Update
while ? Condition first
do-while ? Execute first