C# for and foreach Loops: Complete Guide with Examples

Loops are one of the most important concepts in programming. They allow you to execute the same block of code multiple times without writing duplicate code. Whether you’re printing numbers, processing a list of names, or calculating totals, loops make your programs shorter, cleaner, and more efficient.

C# provides several types of loops, but two of the most commonly used are:

  • for loop
  • foreach loop

Although both repeat code, they are designed for different situations. Understanding when and how to use each one is an essential skill for every C# programmer.

In this tutorial, you’ll learn:

  • What for and foreach loops are
  • Their syntax
  • How each part works
  • When to use each loop
  • Practical examples
  • Nested loops
  • Common mistakes
  • Best practices
  • Differences between the two loops

By the end of this guide, you’ll know exactly which loop to choose for different programming tasks.


What Is a Loop?

A loop repeatedly executes a block of code until a condition becomes false.

Instead of writing:

Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");
Console.WriteLine("Hello");

You can simply write:

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Hello");
}

The output is:

Hello
Hello
Hello
Hello
Hello

The loop saves time and makes your code much easier to maintain.

Types of Loops in C#

C# provides four main loop statements:

  • for – Repeats a block of code a specific number of times or while a condition remains true. It is ideal when you know how many iterations you need.
  • foreach – Iterates through each element in a collection, such as an array, list, or dictionary. It’s the preferred choice when you simply want to process every item.
  • while – Repeats a block of code as long as a condition is true. It’s commonly used when the number of iterations isn’t known beforehand.
  • do...while – Similar to while, but it executes the loop body at least once before checking the condition.

This article focuses on the for and foreach loops. The while and do...while loops are covered separately.


The C# for Loop

The for loop is used when you know in advance how many times you want to repeat a block of code.

Syntax

for (initialization; condition; update)
{
    // Code to execute
}

Three Parts of a for Loop

for (int i = 0; i < 5; i++)

Let’s break this down.

1. Initialization

int i = 0;

Runs only once.

Creates the loop variable.

2. Condition

i < 5

Before every iteration, C# checks this condition.

  • True → continue
  • False → stop

3. Update

i++

Runs after every iteration.

Usually increments or decrements the loop variable.


How a for Loop Works

Example:

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine(i);
}

Execution:

Iteration 1

i = 1
Condition: 1 <= 3True
Print 1
i becomes 2

Iteration 2

i = 2
Condition: True
Print 2
i becomes 3

Iteration 3

i = 3
Condition: True
Print 3
i becomes 4

Iteration 4

Condition: 4 <= 3False
Loop stops

Output

1
2
3

Example 1: Print Numbers

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine(i);
}

Output

1
2
3
4
5
6
7
8
9
10

Example 2: Count Backwards

for (int i = 10; i >= 1; i--)
{
    Console.WriteLine(i);
}

Output

10
9
8
7
6
5
4
3
2
1

Example 3: Print Even Numbers

for (int i = 2; i <= 20; i += 2)
{
    Console.WriteLine(i);
}

Output

2
4
6
8
10
12
14
16
18
20

Example 4: Multiplication Table

int number = 7;

for (int i = 1; i <= 10; i++)
{
    Console.WriteLine($"{number} × {i} = {number * i}");
}

Output

7 × 1 = 7
7 × 2 = 14
...
7 × 10 = 70

Example 5: Calculate a Sum

int sum = 0;

for (int i = 1; i <= 100; i++)
{
    sum += i;
}

Console.WriteLine(sum);

Output

5050

Example 6: Loop Through an Array Using Indexes

string[] fruits =
{
    "Apple",
    "Banana",
    "Orange"
};

for (int i = 0; i < fruits.Length; i++)
{
    Console.WriteLine(fruits[i]);
}

Output

Apple
Banana
Orange

Notice how we use the index i to access array elements.


Skipping Iterations with continue

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        continue;

    Console.WriteLine(i);
}

Output

1
2
4
5

continue skips the rest of the current iteration and moves to the next one.


Exiting a Loop with break

for (int i = 1; i <= 10; i++)
{
    if (i == 6)
        break;

    Console.WriteLine(i);
}

Output

1
2
3
4
5

break immediately exits the loop.


Infinite for Loops

for (;;)
{
    Console.WriteLine("Running...");
}

Since there is no stopping condition, this loop runs forever until interrupted.


Nested for Loops

A loop can contain another loop.

for (int row = 1; row <= 3; row++)
{
    for (int column = 1; column <= 4; column++)
    {
        Console.Write("* ");
    }

    Console.WriteLine();
}

Output

* * * *
* * * *
* * * *

Nested loops are commonly used for working with grids, tables, and matrices.


The C# foreach Loop

The foreach loop is designed specifically for iterating through every element in a collection.

Instead of using indexes, C# automatically gives you each item one by one.


Syntax

foreach (dataType variable in collection)
{
    // Code
}

Example

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

How foreach Works

Suppose we have:

string[] fruits =
{
    "Apple",
    "Banana",
    "Orange"
};

Execution:

fruit = Apple
Print Apple

fruit = Banana
Print Banana

fruit = Orange
Print Orange

Output

Apple
Banana
Orange

No indexes are needed.


Example 1: Print Student Names

string[] students =
{
    "Alice",
    "Bob",
    "Charlie"
};

foreach (string student in students)
{
    Console.WriteLine(student);
}

Output

Alice
Bob
Charlie

Example 2: Sum Numbers

int[] numbers = { 10, 20, 30, 40 };

int total = 0;

foreach (int number in numbers)
{
    total += number;
}

Console.WriteLine(total);

Output

100

Example 3: Count Characters

string word = "Programming";

foreach (char letter in word)
{
    Console.WriteLine(letter);
}

Output

P
r
o
g
r
a
m
m
i
n
g

A string is a collection of characters, so foreach can iterate through it.


Example 4: Iterate Through a List

List<string> colors = new List<string>()
{
    "Red",
    "Green",
    "Blue"
};

foreach (string color in colors)
{
    Console.WriteLine(color);
}

Output

Red
Green
Blue

Example 5: Loop Through a Dictionary

Dictionary<string, int> ages = new Dictionary<string, int>()
{
    { "Alice", 25 },
    { "Bob", 30 },
    { "Charlie", 22 }
};

foreach (var person in ages)
{
    Console.WriteLine($"{person.Key}: {person.Value}");
}

Output

Alice: 25
Bob: 30
Charlie: 22

Can You Modify Items in a foreach Loop?

No.

The iteration variable is read-only.

Incorrect:

foreach (int number in numbers)
{
    number++;
}

This causes a compilation error.

If you need to modify elements, use a for loop instead.

for (int i = 0; i < numbers.Length; i++)
{
    numbers[i]++;
}

When Should You Use for?

Use a for loop when:

  • You need the index.
  • You want to move forward or backward.
  • You need to skip elements intentionally.
  • You want complete control over the iteration.
  • You need to modify collection elements by index.

Example:

for (int i = numbers.Length - 1; i >= 0; i--)
{
    Console.WriteLine(numbers[i]);
}

When Should You Use foreach?

Use foreach when:

  • You simply need to read every item.
  • You don’t care about indexes.
  • You want cleaner, easier-to-read code.
  • You want to avoid index-related mistakes.

Example:

foreach (string city in cities)
{
    Console.WriteLine(city);
}

for vs foreach

Featureforforeach
Uses indexes
Modify elementsUsually ✘
ReadabilityGoodExcellent
Reverse iteration
Custom step size
SimplicityModerateVery easy

Common Mistakes

1. Using <= Instead of <

Incorrect:

for (int i = 0; i <= numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

This attempts to access an index that doesn’t exist and throws an IndexOutOfRangeException.

Correct:

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

2. Forgetting to Update the Loop Variable

for (int i = 0; i < 5;)
{
    Console.WriteLine(i);
}

Since i never changes, the loop runs forever.


3. Changing Collection Size During foreach

foreach (string item in names)
{
    names.Add("New");
}

This throws an InvalidOperationException because the collection is modified during enumeration.


Best Practices

  • Choose foreach when you only need to read items.
  • Use meaningful variable names.
  • Avoid unnecessary nested loops.
  • Keep loop bodies short and focused.
  • Use break and continue only when they improve readability.
  • Be careful with loop boundaries to avoid off-by-one errors.
  • Prefer var in foreach when the element type is obvious:
foreach (var fruit in fruits)
{
    Console.WriteLine(fruit);
}

Practice Exercises

Try solving these exercises on your own:

  1. Print numbers from 1 to 50.
  2. Print all odd numbers between 1 and 100.
  3. Calculate the factorial of a number using a for loop.
  4. Find the largest number in an array using foreach.
  5. Count how many vowels are in a string using foreach.
  6. Print a right triangle of asterisks (*) using nested for loops.
  7. Reverse an array using a for loop.
  8. Calculate the average of values in a list using foreach.

Summary

The for and foreach loops are fundamental tools for repeating code in C#.

The for loop provides maximum flexibility. It lets you control the starting value, stopping condition, iteration direction, and step size, making it ideal when you need indexes or want to modify elements.

The foreach loop focuses on simplicity and readability. It automatically visits every element in a collection, reducing the chance of index-related errors. It is the preferred choice when you only need to read items from arrays, lists, dictionaries, strings, and other enumerable collections.

A good rule of thumb is:

  • Use foreach when processing every item in a collection without changing it.
  • Use for when you need indexes, custom iteration logic, reverse traversal, or element modification.

Mastering these two loops will give you a strong foundation for solving many common programming problems and will prepare you to work confidently with collections, arrays, and more advanced C# features.