C# For Loop

Welcome to The Coding College! In this tutorial, we’ll learn about the for loop in C#. The for loop is one of the most commonly used looping structures in programming, as it efficiently executes a block of code repeatedly for a specified number of times.

By the end of this guide, you will:

  • Understand what a for loop is.
  • Learn the syntax of the for loop.
  • Practice with examples to solidify your understanding.

Let’s dive in! 🚀

What is a For Loop?

A for loop allows you to repeatedly execute a block of code a fixed number of times. It is particularly useful when the number of iterations is known before the loop begins.

Syntax of For Loop

Here’s the basic syntax of a for loop in C#:

for (initialization; condition; increment/decrement)
{
    // Code to be executed repeatedly
}

Explanation of the Parameters:

  1. Initialization: Sets the starting value for the loop control variable.
  2. Condition: Specifies the condition that must be true for the loop to execute.
  3. Increment/Decrement: Updates the loop control variable after each iteration.

How It Works:

  1. The initialization is executed only once at the start.
  2. The condition is evaluated; if it’s true, the loop body executes.
  3. After the loop body executes, the increment/decrement updates the control variable.
  4. Steps 2 and 3 repeat until the condition becomes false.

Example 1: Simple For Loop

Let’s print numbers from 1 to 5 using a for loop.

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine("Number: " + i);
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Explanation:

  1. int i = 1 initializes the loop variable i to 1.
  2. i <= 5 checks if i is less than or equal to 5.
  3. i++ increments the value of i by 1 after each iteration.

Example 2: For Loop with Decrement

We can also decrement a loop variable. Let’s print numbers from 5 to 1.

using System;

class Program
{
    static void Main()
    {
        for (int i = 5; i >= 1; i--)
        {
            Console.WriteLine("Number: " + i);
        }
    }
}

Output:

Number: 5  
Number: 4  
Number: 3  
Number: 2  
Number: 1  

Explanation:

  1. int i = 5 initializes i to 5.
  2. i >= 1 checks if i is greater than or equal to 1.
  3. i-- decrements the value of i by 1 after each iteration.

Example 3: For Loop with Multiple Variables

You can initialize multiple variables in the for loop.

using System;

class Program
{
    static void Main()
    {
        for (int i = 1, j = 10; i <= 5; i++, j--)
        {
            Console.WriteLine("i: " + i + ", j: " + j);
        }
    }
}

Output:

i: 1, j: 10  
i: 2, j: 9  
i: 3, j: 8  
i: 4, j: 7  
i: 5, j: 6 

Explanation:

  • Two variables i and j are initialized.
  • i increments while j decrements in each iteration.

Example 4: Skipping Iterations Using continue

The continue statement skips the current iteration of the loop and jumps to the next one.

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            if (i == 3)
            {
                continue; // Skip iteration when i = 3
            }

            Console.WriteLine("Number: " + i);
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 4  
Number: 5

Explanation:

  • When i == 3, the continue statement skips the current iteration.

Example 5: Exiting the Loop Using break

The break statement terminates the loop entirely.

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            if (i == 4)
            {
                break; // Exit loop when i = 4
            }

            Console.WriteLine("Number: " + i);
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 3

Explanation:

  • When i == 4, the break statement stops the loop execution.

When to Use a For Loop?

The for loop is ideal when:

  1. You know the exact number of iterations in advance.
  2. You need a simple and concise loop structure.
  3. You want to work with multiple loop variables.

Difference Between While and For Loop

FeatureFor LoopWhile Loop
InitializationDone in the loop headerDone outside the loop
ConditionChecked before each iterationChecked before each iteration
Control VariableUpdated in the loop headerUpdated inside the loop body
Use CaseKnown number of iterationsUnknown number of iterations

Best Practices for For Loops

  1. Use clear and meaningful variable names for loop control variables.
  2. Avoid infinite loops by ensuring the condition becomes false.
  3. Use break and continue statements wisely.
  4. Keep the loop logic simple and clean for better readability.

Conclusion

The for loop in C# is a versatile tool for performing repetitive tasks efficiently. Whether you need to iterate a fixed number of times, process arrays, or implement complex logic, the for loop provides a concise and structured way to achieve your goal.

For more C# tutorials and coding tips, visit The Coding College—your go-to platform for learning programming.

Leave a Comment