C# Loops

Repeat work with for, foreach, while and do-while loops, control them with break and continue, nest loops for tables and grids, and pick the right loop for each job.

Lesson 7 of 43Beginner18 min read

Computers are brilliant at repetition. Printing a hundred invoices, checking every item in a basket, retrying a download, asking for input until it's valid: all of these use loops, which run a block of code again and again.

C# has four loops, each suited to a different situation. for is ideal when you know how many times to repeat or need a counter. foreach walks through every item in a collection, such as an array or list, and is the loop you'll use most. while repeats as long as a condition stays true, which suits situations where you don't know the count in advance. do-while is like while but always runs at least once.

Inside any loop, break stops the loop early and continue skips to the next repetition. In this lesson you'll write each kind of loop, build running totals, nest loops to make tables, and learn to avoid the two classic loop bugs: infinite loops and off-by-one errors.

for loops

C#
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Line {i}");
}

A for loop has three parts, separated by semicolons:

  1. Initialiser: int i = 1 runs once, before the loop starts.
  2. Condition: i <= 5 is checked before every repetition; the loop ends when it's false.
  3. Iterator: i++ runs after each repetition.

Count down with for (int i = 10; i > 0; i--), or step by twos with i += 2. When looping over an array by index, use i < array.Length, because the last index is one less than the length.

foreach loops

C#
string[] fruits = { "apple", "banana", "cherry" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

foreach gives you each item in turn, with no index to manage, so there's no chance of an off-by-one mistake. It works with arrays, lists, dictionaries, strings (one char at a time) and anything else that can be enumerated. You can write foreach (var fruit in fruits) and let the compiler infer the type.

while, do-while, break and continue

C#
int attempts = 0;
while (attempts < 3)
{
    attempts++;
}

do
{
    Console.Write("Continue? ");
} while (Console.ReadLine() == "y");
  • while checks the condition first, so its body might never run.
  • do-while checks after, so the body always runs at least once, which suits menus and prompts.
  • break exits the innermost loop immediately.
  • continue skips the rest of this repetition and moves on to the next.

Nested loops and leaving them early

A loop inside another loop is common for grids, tables and comparing every item with every other item. The inner loop runs completely for each repetition of the outer loop, so two loops of 1,000 items each run the inner body a million times.

break only leaves the innermost loop. To stop both loops as soon as you find something, the clearest approach is to put them in a method and return:

C#
static (int Row, int Col)? Find(int[,] grid, int target)
{
    for (int r = 0; r < grid.GetLength(0); r++)
        for (int c = 0; c < grid.GetLength(1); c++)
            if (grid[r, c] == target)
                return (r, c);   // leaves both loops at once
    return null;                 // not found
}

The alternative is a bool found flag that the outer loop's condition also checks, which works but is easier to get wrong. C# does have goto, but it's rarely used in modern code.

Variables declared in a loop, including the i in a for loop, only exist inside that loop. If you need the final value after the loop ends, declare the variable before the loop starts.

C# Control Flow Syntax

Loop forms

for (int i = 0; i < 10; i++) { }
for (int i = 10; i >= 0; i -= 2) { }
foreach (var item in items) { }
while (condition) { }
do { } while (condition);
break;      // leave the loop
continue;   // next repetition

C# Control Flow Summary

  • for has an initialiser, a condition and an iterator; it suits counted loops.
  • foreach visits every item of a collection without an index.
  • while checks first; do-while always runs at least once.
  • break exits a loop; continue skips to the next repetition.
  • Loop over arrays with i < Length to avoid going past the last index.

C# Control Flow Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Totals with foreach

C#
decimal[] prices = { 4.99m, 12.50m, 3.25m, 20.00m };
decimal total = 0;
decimal highest = prices[0];

foreach (decimal price in prices)
{
    total += price;
    if (price > highest)
    {
        highest = price;
    }
}

Console.WriteLine($"Items: {prices.Length}");
Console.WriteLine($"Total: {total:F2}");
Console.WriteLine($"Highest: {highest:F2}");
Console.WriteLine($"Average: {total / prices.Length:F2}");
Output
Items: 4
Total: 40.74
Highest: 20.00
Average: 10.19
Line-by-line explanation
  1. Lines 2 to 3Variables that collect results start before the loop.
  2. Line 5foreach gives each price in turn.
  3. Line 7A running total adds every price.
  4. Lines 8 to 11The highest value so far is replaced when a bigger one appears.
  5. Line 1740.74 divided by 4 is 10.185, which rounds to 10.19 with F2.
Example 2

for loops and a times table

C#
for (int i = 10; i > 0; i -= 3)
{
    Console.Write($"{i} ");
}
Console.WriteLine();

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 4; col++)
    {
        Console.Write($"{row * col,4}");
    }
    Console.WriteLine();
}
Output
10 7 4 1 
   1   2   3   4
   2   4   6   8
   3   6   9  12
Line-by-line explanation
  1. Line 1Start at 10 and subtract 3 each time while i is above 0.
  2. Lines 7 to 14The inner loop runs completely for each row of the outer loop.
  3. Line 11,4 right-aligns each number in four characters to form columns.
  4. Line 13A new line after each row.
Example 3

while, break and continue

C#
int[] orders = { 120, -5, 80, 0, 300, 45 };
int processed = 0;

foreach (int amount in orders)
{
    if (amount <= 0)
    {
        Console.WriteLine($"Skipping invalid amount {amount}");
        continue;
    }
    if (amount > 250)
    {
        Console.WriteLine("Large order found, stopping for review");
        break;
    }
    processed++;
}
Console.WriteLine($"Processed {processed} orders");

int balance = 100;
int months = 0;
while (balance < 150)
{
    balance += balance / 10;
    months++;
}
Console.WriteLine($"{months} months to reach {balance}");
Output
Skipping invalid amount -5
Skipping invalid amount 0
Large order found, stopping for review
Processed 2 orders
5 months to reach 160
Line-by-line explanation
  1. Line 9continue jumps straight to the next order.
  2. Line 14break leaves the loop, so 45 is never checked.
  3. Line 22The while loop runs until the condition becomes false; the number of repetitions isn't known in advance.
  4. Line 24Integer division: 10% growth rounded down each month: 110, 121, 133, 146, 160.

Common C# Control Flow Mistakes

Going one past the end

Don't
for (int i = 0; i <= items.Length; i++)   // IndexOutOfRangeException on the last pass
Do
for (int i = 0; i < items.Length; i++)

An infinite while loop

Don't
int n = 0;
while (n < 5)
{
    Console.WriteLine(n);   // n never changes, so this never ends
}
Do
int n = 0;
while (n < 5)
{
    Console.WriteLine(n);
    n++;
}

Removing items inside foreach

Don't
foreach (var item in list)
{
    if (item.Expired) list.Remove(item);   // InvalidOperationException: collection was modified
}
Do
list.RemoveAll(item => item.Expired);

C# Control Flow in Real Projects

Loops in real programs

Batch jobs loop over thousands of records to send emails or update prices. Games run a main loop many times per second to update and draw the world. Retry logic uses a while loop with a counter and a delay. In everyday code, foreach over lists returned from a database is by far the most common loop, and LINQ, covered later, replaces many simple loops with one-line queries.

C# Control Flow FAQ

What is the difference between for and foreach in C#?

for gives you an index and full control over where to start, where to stop and how to step. foreach hands you each item in turn and works with any collection, including ones without indexes such as HashSet<T>. Use foreach to read every item and for when you need the index, want to change array items or need to go backwards.

How do I break out of two nested loops in C#?

break only exits the innermost loop. Move the loops into a method and use return when you find what you need, or set a bool flag and check it in the outer loop's condition. The method approach is usually the easiest to read.

Why do I get "Collection was modified; enumeration operation may not execute"?

You added or removed items from a list while a foreach was looping over it. Loop over a copy with foreach (var x in list.ToList()), loop backwards with a for loop when removing, or use list.RemoveAll(predicate) to remove matching items in one call.

When should I use a do-while loop?

Use do-while when the body must run at least once before the condition makes sense, such as showing a menu and then asking whether to go again. For most other loops, while or for is clearer because the condition is visible at the top.

How do I loop a fixed number of times in C#?

Use a for loop: for (int i = 0; i < 5; i++) { ... } runs five times, with i going from 0 to 4. If you want to count from 1, write for (int i = 1; i <= 5; i++). foreach (var i in Enumerable.Range(1, 5)) does the same with a sequence of numbers.

C# Control Flow Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the loop so it visits every name.

string[] names = { "Ana", "Ben" };
 (string name in names)
{
    Console.WriteLine(name);
}
Predict the outputeasy

How many lines does this print?

for (int i = 0; i < 4; i++)
{
    Console.WriteLine(i);
}
Predict the outputmedium

What does this print?

int sum = 0;
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;
    sum += i;
}
Console.WriteLine(sum);
Multiple choicemedium

Which loop always runs its body at least once?

Multiple choicehard

Why does removing items from a list inside foreach fail?

C# Control Flow Quiz

5 questions to check what you learned.

  1. What does break do inside a loop?

    • Exits the loop immediately
    • Skips one repetition
    • Restarts the loop
    • Pauses the program
  2. What does continue do?

    • Ends the program
    • Exits all loops
    • Repeats the same repetition
    • Skips the rest of the current repetition and starts the next
  3. Which condition safely loops over every index of an array arr?

    • i <= arr.Length
    • i < arr.Length - 1
    • i != arr.Length + 1
    • i < arr.Length
  4. Which loop is best when you don't know how many repetitions you'll need?

    • for
    • while
    • foreach
    • None
  5. How many times does the inner line run? for (i = 0; i < 3; i++) for (j = 0; j < 4; j++) count++;

    • 12
    • 7
    • 3
    • 4