C# For Loop

Repeating code a specific number of times

🔢 What is a For Loop?

A for loop repeats code a specific number of times. It's perfect when you know exactly how many iterations you need, combining initialization, condition, and increment in one compact statement.


// Simple for loop
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"Iteration: {i}");
}
                                    

Output:

Iteration: 1

Iteration: 2

Iteration: 3

Iteration: 4

Iteration: 5

For Loop Components

🎬

Initialization

Set starting value

for (int i = 0; ...; ...)
{
    // i starts at 0
}

Condition

Check if loop should continue

for (...; i < 10; ...)
{
    // Run while i < 10
}
⬆️

Increment

Update counter after each loop

for (...; ...; i++)
{
    // i increases by 1
}
🔁

Foreach Loop

Iterate through collections

foreach (var item in list)
{
    Console.WriteLine(item);
}

🔹 Basic For Loop

A standard for loop includes three parts: an initializer, a condition, and an iterator. It executes the initializer once, checks the condition before each iteration, and runs the iterator after each pass. This structure is ideal for counting tasks, iterating arrays, or repeating code a predetermined number of times, providing precise control over the loop's execution flow.

// Count from 0 to 4
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"i = {i}");
}

// Count from 1 to 10
for (int num = 1; num <= 10; num++)
{
    Console.WriteLine($"Number: {num}");
}

// Count backwards
for (int countdown = 5; countdown >= 1; countdown--)
{
    Console.WriteLine(countdown);
}
Console.WriteLine("Liftoff!");

Output:

i = 0

i = 1

i = 2

i = 3

i = 4

Number: 1

...

5

4

3

2

1

Liftoff!

🔹 Loop with Different Increments

The increment expression in a for loop can be modified to step by any value. Instead of the typical i++, you can use i += 2 to count even numbers, or i += 5 to count in multiples of five. This flexibility allows you to traverse ranges, skip elements, or create custom counting patterns efficiently within a single loop construct.

// Count by 2s (even numbers)
for (int i = 0; i <= 10; i += 2)
{
    Console.WriteLine(i);
}

// Count by 5s
for (int i = 0; i <= 20; i += 5)
{
    Console.WriteLine($"Multiple of 5: {i}");
}

// Decrease by 2
for (int i = 10; i >= 0; i -= 2)
{
    Console.WriteLine(i);
}

Output:

0

2

4

6

8

10

Multiple of 5: 0

Multiple of 5: 5

...

🔹 Looping Through Arrays

For loops are commonly used to iterate over array elements by index. By using the array's Length property as the loop condition, you can automatically process every item regardless of the array's size. This method is efficient for tasks like calculating sums, finding values, or displaying all elements in a collection sequentially.

// Loop through array
string[] fruits = { "Apple", "Banana", "Orange", "Mango" };

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

// Sum array elements
int[] numbers = { 10, 20, 30, 40, 50 };
int sum = 0;

for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}
Console.WriteLine($"Total sum: {sum}");

Output:

1. Apple

2. Banana

3. Orange

4. Mango

Total sum: 150

🔹 Nested For Loops

Nested loops consist of one loop inside another, creating a grid or matrix iteration pattern. The inner loop completes all its cycles for each single iteration of the outer loop. This is perfect for generating multiplication tables, printing patterns like triangles or grids, or processing two-dimensional data structures such as tables and matrices.

// Multiplication table
for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        Console.Write($"{i * j}\t");
    }
    Console.WriteLine(); // New line after each row
}

// Star pattern
for (int i = 1; i <= 4; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write("* ");
    }
    Console.WriteLine();
}

Output:

1 2 3

2 4 6

3 6 9

*

* *

* * *

* * * *

🔹 Break and Continue in For Loops

The break and continue statements control loop execution flow precisely in C#. The break statement immediately exits the entire loop when a specific condition is met, stopping all further iterations. Conversely, the continue statement skips only the current iteration and proceeds directly to the next cycle of the loop. This allows developers to efficiently handle edge cases, filter data, or exit loops early based on runtime logic, optimizing performance and code clarity.

// Using break
for (int i = 1; i <= 10; i++)
{
    if (i == 6)
    {
        Console.WriteLine("Breaking at 6");
        break;
    }
    Console.WriteLine(i);
}

// Using continue
for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        Console.WriteLine("Skipping 3");
        continue;
    }
    Console.WriteLine($"Processing: {i}");
}

Output:

1

2

3

4

5

Breaking at 6

Processing: 1

Processing: 2

Skipping 3

Processing: 4

Processing: 5

🔹 Foreach Loop

The foreach loop provides a safe and readable way to iterate over collections in C# without manual index management. It automatically accesses each element sequentially from arrays, lists, or other enumerable types, preventing common errors like off-by-one mistakes. Since it is read-only by design, it ensures the original collection structure remains unaltered during iteration. This makes foreach ideal for scenarios where you need to process or display each item without modifying the source data, enhancing both safety and code maintainability.

// Foreach with array
string[] colors = { "Red", "Green", "Blue", "Yellow" };

foreach (string color in colors)
{
    Console.WriteLine($"Color: {color}");
}

// Foreach with list
int[] scores = { 85, 92, 78, 95, 88 };
int total = 0;

foreach (int score in scores)
{
    total += score;
}
Console.WriteLine($"Average score: {total / scores.Length}");

Output:

Color: Red

Color: Green

Color: Blue

Color: Yellow

Average score: 87

🔹 Practical Examples

While loops are fundamental for real-world programming tasks where repetition is conditional. Key applications include input validation (re-prompting a user until correct data is entered), accumulating a sum until a threshold is met, implementing password attempts with limited tries, or running a main game loop. Their flexibility makes them suitable for event-driven programming, processing streams of data, and controlling program states where the exact number of required repetitions cannot be predetermined before runtime.

// Calculate factorial
int number = 5;
int factorial = 1;

for (int i = 1; i <= number; i++)
{
    factorial *= i;
}
Console.WriteLine($"Factorial of {number} is {factorial}");

// Find even numbers in range
Console.WriteLine("Even numbers from 1 to 10:");
for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0)
    {
        Console.Write($"{i} ");
    }
}
Console.WriteLine();

// Generate Fibonacci sequence
int n = 7;
int a = 0, b = 1;
Console.Write("Fibonacci: ");

for (int i = 0; i < n; i++)
{
    Console.Write($"{a} ");
    int temp = a;
    a = b;
    b = temp + b;
}

Output:

Factorial of 5 is 120

Even numbers from 1 to 10:

2 4 6 8 10

Fibonacci: 0 1 1 2 3 5 8

🧠 Test Your Knowledge

How many times will this loop run?
for (int i = 0; i < 5; i++)