Loops in C#
From the C# Programming Language cheat sheet · Control Flow · verified Jul 2026
Loops
Iteration and repetition
csharp
// For loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// While loop
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
// Do-while (runs at least once)
do
{
Console.WriteLine("Run at least once");
} while (false);
// Foreach loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}💡 Use foreach when you don't need the index
⚡ break exits loop, continue skips to next iteration
📌 While for unknown iterations, for when count is known
🟢 Do-while guarantees at least one execution