For Loop in CSharp

The for loop is a fundamental control flow statement in C# used for repetitive tasks. In this article, we’ll explore the syntax, usage, and versatility of the for loop with comprehensive examples.

Syntax of the for Loop

The for loop in C# consists of three essential parts:

for (initialization; condition; iteration)
{
    // Loop body
}
  • initialization: Initialize loop variables or values.
  • condition: Define the exit condition; loop continues while true.
  • iteration: Modify loop variables for each iteration.

Basic Usage of the for Loop

Example 1: Counting Numbers

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

This for loop counts and displays numbers from 1 to 5.

Advanced Usage of the for Loop

Example 2: Summing Numbers

int sum = 0;
for (int i = 1; i <= 10; i++)
{
    sum += i;
}
Console.WriteLine("Sum of numbers from 1 to 10: " + sum);

This for loop calculates the sum of numbers from 1 to 10.

Nested for Loops

You can nest for loops for more complex iterations, such as iterating through a 2D array.

Example 3: Nested Loop

for (int i = 1; i <= 3; i++)
{
    for (int j = 1; j <= 3; j++)
    {
        Console.WriteLine($"i: {i}, j: {j}");
    }
}

This nested for loop prints combinations of i and j from 1 to 3.

Loop Control Statements

Control the flow within a for loop using control statements like break and continue.

Example 4: Using break

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        break; // Exits the loop when i equals 3
    }
    Console.WriteLine(i);
}

In this example, the loop exits when i equals 3.

Example 5: Using continue

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
    {
        continue; // Skips iteration when i equals 3
    }
    Console.WriteLine(i);
}

Here, the loop skips the iteration when i equals 3.

Conclusion

The for loop is a versatile and powerful tool for handling repetitive tasks in C#. With its structured syntax and various use cases, mastering the for loop is essential for efficient and concise code development.