C# Loops Documentation

Mastering all types of loops in C# programming language

Back to Dashboard

for Loop

Executes a block of code a specified number of times.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
Output: 0 1 2 3 4

while Loop

Executes a block of code while a condition is true.

int j = 0;
while (j < 5)
{
    Console.WriteLine(j);
    j++;
}
Output: 0 1 2 3 4

do-while Loop

Executes a block of code once, then repeats while a condition is true.

int k = 0;
do
{
    Console.WriteLine(k);
    k++;
} while (k < 5);
Output: 0 1 2 3 4

foreach Loop

Iterates through each element in a collection or array.

string[] cars = {"Volvo", "BMW", "Ford"};
foreach (string car in cars)
{
    Console.WriteLine(car);
}
Output: Volvo BMW Ford

Nested Loops

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}");
    }
}
Output: i:1 j:1, i:1 j:2, i:2 j:1, ...

Loop Control

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);
}
Output: 1 3