for loop in C#

The for loop in C# is used to repeat a block of code a known number of times. It is one of the most common loop statements because it keeps initialization, condition checking, and updating in one compact line. This makes it useful for counting, indexing arrays, processing ranges, generating tables, and running repeated operations.

A for loop is especially useful when you know where the loop should start, when it should stop, and how the loop variable should change after each iteration. If the number of repetitions is controlled by an index, a counter, or a fixed range, for is usually a natural choice.


What Is for loop in C#?

A for loop repeats code while a condition remains true. It has three main parts: initialization, condition, and iteration. These three parts are written inside parentheses after the for keyword.

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

This loop prints numbers from 1 to 5. The variable i starts at 1, the loop continues while i <= 5, and i++ increases the value after each iteration.

Syntax of for loop

for (initialization; condition; iteration)
{
    // loop body
}
PartMeaning
InitializationRuns once before the loop starts
ConditionChecked before each iteration
IterationRuns after each loop body execution
Loop bodyCode that repeats

If the condition is false before the first iteration, the loop body does not run even once. This is important when working with empty arrays, zero counts, or invalid ranges.

Flow of for loop Execution

The execution flow of a for loop is predictable. First, the initialization runs. Second, the condition is checked. Third, the loop body runs if the condition is true. Fourth, the iteration expression runs. Then the condition is checked again.

  • Initialize the loop variable.
  • Check the loop condition.
  • Execute the loop body if the condition is true.
  • Run the iteration expression.
  • Repeat until the condition becomes false.

for loop with Arrays

The for loop is commonly used with arrays because arrays use zero-based indexing. The first element is at index 0, and the last element is at index Length - 1.

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

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

The condition i < numbers.Length prevents the loop from going outside the array. Using <= numbers.Length would cause an index error because the last valid index is one less than the length.

Reverse for loop

A for loop can also count backward. This is useful when processing items from the end, reversing output, or removing items from a list by index.

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

Here, the loop starts at 5 and decreases i after each iteration. The loop stops when i becomes less than 1.

Nested for loop

A nested for loop means one loop is placed inside another. Nested loops are used for tables, grids, matrices, two-dimensional arrays, patterns, and coordinate-based processing.

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 3; col++)
    {
        Console.Write($"{row},{col} ");
    }

    Console.WriteLine();
}

For every single iteration of the outer loop, the inner loop runs completely. This means nested loops can grow expensive quickly. A loop with 100 rows and 100 columns runs 10,000 inner operations.

Infinite for loop

A for loop can be made infinite by leaving the condition empty. Infinite loops are used in some servers, embedded systems, game loops, and background processing tasks, but they must have a safe exit path.

for (;;)
{
    string? input = Console.ReadLine();

    if (input == "exit")
    {
        break;
    }
}

The loop continues forever until the user enters exit. The break statement is what safely exits the loop.

break and continue in for loop

The break statement exits the loop immediately. The continue statement skips the current iteration and moves to the next one.

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

    if (i == 8)
    {
        break;
    }

    Console.WriteLine(i);
}

In this example, 5 is skipped and the loop stops completely when 8 is reached.

Understanding the Three Parts of for loop

The three parts of a for loop are not just syntax. They describe the complete lifecycle of the loop. The initialization creates the starting state. The condition decides whether another iteration should run. The iteration expression moves the loop toward completion.

For example, in for (int i = 0; i < 10; i++), the loop starts at zero, runs while i is less than ten, and increases i by one after every pass. This pattern is common because it matches zero-based indexing in arrays and lists.

for (int i = 0; i < 10; i++)
{
    Console.WriteLine($"Current index: {i}");
}

The loop variable usually belongs only to the loop. This is good because it keeps the counter from being accidentally used or modified somewhere else in the method.

Off-by-One Errors in for loop

An off-by-one error happens when a loop runs one time too many or one time too few. This is one of the most common loop bugs. It usually comes from using the wrong comparison operator or misunderstanding the last valid index.

For arrays and lists, the safe condition is normally i < collection.Count or i < array.Length. The last valid index is Count - 1, not Count.

List<string> names = new() { "Asha", "Ravi", "Meera" };

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

This loop runs for indexes 0, 1, and 2. It does not try index 3, because that would be outside the list.

for loop with Multiple Variables

A for loop can use multiple variables in the initialization and iteration sections. This is useful when two counters need to move together, such as comparing values from both ends of an array.

int[] values = { 1, 2, 3, 2, 1 };

for (int left = 0, right = values.Length - 1; left < right; left++, right--)
{
    if (values[left] != values[right])
    {
        Console.WriteLine("Not symmetrical");
        break;
    }
}

This style should be used only when it improves clarity. If multiple loop variables make the loop harder to understand, split the logic into smaller methods or use clearer variable names.

Modifying a List Inside for loop

A for loop is sometimes used when items must be removed from a list by index. When removing items, looping backward is usually safer because removing an item changes the indexes of items after it.

List<int> numbers = new() { 1, 2, 3, 4, 5, 6 };

for (int i = numbers.Count - 1; i >= 0; i--)
{
    if (numbers[i] % 2 == 0)
    {
        numbers.RemoveAt(i);
    }
}

By moving from the end to the beginning, the loop avoids skipping elements after removal. This is one area where for can be better than foreach, because foreach does not allow modifying the collection during enumeration.

for loop Performance Considerations

For normal application code, readability is usually more important than micro-optimizing a loop. But loop performance matters when the body runs thousands or millions of times. A small expensive operation inside a loop can become costly because it is repeated many times.

A practical rule is to move work outside the loop when it does not change per iteration. Avoid repeated database calls, file reads, network requests, or heavy calculations inside a loop unless they are truly required. The loop structure may be correct, but the repeated work can still make the program slow.

The cost of a loop is not only the number of iterations. It is the cost of the loop body multiplied by those iterations.

When to Use for loop Instead of foreach

Use for when the index matters. This includes accessing neighboring elements, modifying values by position, looping backward, skipping by custom steps, or removing items by index. Use foreach when you only need to read each item in a collection without caring about its position.

NeedBetter Loop
Need indexfor
Read all items simplyforeach
Loop backwardfor
Remove by indexfor
Cleaner collection traversalforeach

Choosing the correct loop is not about which one is more advanced. It is about which one expresses the intention with less risk.

Skipping Values in for loop

The iteration expression does not always have to be i++. You can increase the loop variable by two, five, ten, or any step that fits the problem. This is useful when processing alternate elements, page ranges, batch sizes, or fixed numeric intervals.

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

This loop prints even numbers from 0 to 20. The same idea can be used for pagination, chunk processing, and other cases where the loop should move by a custom step instead of one value at a time.

This keeps the loop precise and intentional.

Common Mistakes with for loop

  • Using <= array.Length instead of < array.Length.
  • Forgetting to update the loop variable, causing an infinite loop.
  • Changing the loop variable inside the loop body without a clear reason.
  • Using nested loops without thinking about performance.
  • Using for when foreach would be simpler and safer.

Best Practices for for loop in C#

Use a for loop when you need an index, a counter, or controlled numeric progression. Keep the condition simple, avoid modifying the loop variable unexpectedly, and use meaningful variable names when the loop does more than basic counting.


Continue learning C# in order
Follow the topic sequence with the previous and next lesson.