Mastering all types of loops in C# programming language
Back to DashboardExecutes a block of code a specified number of times.
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
Executes a block of code while a condition is true.
int j = 0;
while (j < 5)
{
Console.WriteLine(j);
j++;
}
Executes a block of code once, then repeats while a condition is true.
int k = 0;
do
{
Console.WriteLine(k);
k++;
} while (k < 5);
Iterates through each element in a collection or array.
string[] cars = {"Volvo", "BMW", "Ford"};
foreach (string car in cars)
{
Console.WriteLine(car);
}
Loop inside another loop for multi-dimensional iterations.
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
Console.WriteLine($"i: {i}, j: {j}");
}
}
Using break, continue, and goto to control loop execution.
for (int i = 0; i < 10; i++)
{
if (i == 4) break; // Exit loop
if (i % 2 == 0) continue; // Skip even numbers
Console.WriteLine(i);
}