Skip to content

C# - For Loop

A for loop is a repetition control structure that allows you to efficiently execute a block of code a specific number of times. It’s the ideal choice when you know in advance how many times you need to iterate, for example, when processing every item in an array.

The for loop syntax consists of three parts, separated by semicolons:

for (initializer; condition; iterator)
{
// code to be executed in each iteration
}
  • initializer: Executed once before the loop starts. This is where you declare and initialize a loop control variable (e.g., var i = 0).
  • condition: Evaluated before each iteration. If it’s true, the loop body executes. If it’s false, the loop terminates.
  • iterator: Executed after each iteration. This is typically used to increment or decrement the loop variable (e.g., i++).

The execution flow of a for loop can be visualized as follows:

[ Start ]
|
v
[ 1. Initializer (runs once) ]
|
v
[ 2. Condition Check ] --(is true)--> [ 3. Loop Body Executes ]
^ | |
| |(is false) |
| | v
| `---->[ End Loop ] [ 4. Iterator Executes ]
| |
`----------------------------------------`

This example prints numbers from 1 to 5. Notice the use of var for the loop variable and the more common i++ increment operator.

using System;
Console.WriteLine("Starting countdown...");
for (var i = 1; i <= 5; i++)
{
Console.WriteLine($"Value of i: {i}");
}
Console.WriteLine("...Blast off!");

When executed, this code produces:

Starting countdown...
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
...Blast off!

While a for loop is great for iterating with an index, a foreach loop is often a simpler and safer choice for iterating over collections like arrays and lists when you don’t need the index.

var fruits = new string[] { "Apple", "Banana", "Cherry" };
// Using a 'for' loop (needed if you require the index)
Console.WriteLine("\n--- Using for loop ---");
for (var i = 0; i < fruits.Length; i++)
{
Console.WriteLine($"Index {i}: {fruits[i]}");
}
// Using a 'foreach' loop (simpler and preferred for simple iteration)
Console.WriteLine("\n--- Using foreach loop ---");
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}

Loop Control Statements: break and continue

Section titled “Loop Control Statements: break and continue”

You can alter the flow of a loop using control statements:

  • break: Immediately terminates the loop.
  • continue: Skips the rest of the current iteration and proceeds to the next one.
// Example for 'break' and 'continue'
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
// Skip odd numbers
continue;
}
if (i > 8)
{
// Exit the loop if the number is greater than 8
break;
}
Console.WriteLine($"Processing even number: {i}");
}

This will only print Processing even number: 2, 4, 6, and 8.

1. Nested Loops for 2D Data (e.g., Grids, Tables)

Section titled “1. Nested Loops for 2D Data (e.g., Grids, Tables)”

Nested for loops are perfect for working with two-dimensional structures, like printing a multiplication table.

for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
// Use padding to align the numbers neatly
Console.Write($"{i * j, -4}"); // -4 aligns left with 4 spaces
}
Console.WriteLine(); // Move to the next line after each row
}

Use a for loop to modify elements in an array or list in-place.

var numbers = new int[] { 10, 20, 30, 40, 50 };
// Double each number in the array
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] *= 2;
}
Console.WriteLine($"Transformed array: {string.Join(", ", numbers)}");
// Output: Transformed array: 20, 40, 60, 80, 100
  • Off-by-One Errors: Be careful with your condition. Using <= vs. < can be the source of bugs. For a zero-indexed array arr, the condition should be i < arr.Length, not i <= arr.Length.
  • Infinite Loops: Ensure your iterator and condition will eventually lead to the loop’s termination. A condition like for(int i = 0; i >= 0; i++) will run forever.