Bhubaneswar, Odisha, India
+91 8637 274 400

Mastering the For Loop in C#: A Comprehensive Guide with Examples

Mastering the For Loop in C#: A Comprehensive Guide with Examples

Introduction:

The for loop is one of the most fundamental control structures in C# and many other programming languages. It allows you to repeat a block of code a specific number of times, making it essential for tasks that require iteration. This blog post will delve into the for loop in C#, providing a detailed explanation and practical examples to help you grasp its usage effectively.

Are you looking for Live Training in C#?

The upcoming batch for C#.NET is sceduled.

Book Your Seat Now.

Understanding the For Loop

The for loop in C# is used to execute a block of code a certain number of times. It consists of three main parts:

  1. Initialization: Sets the starting point for the loop counter.
  2. Condition: Evaluates the loop condition before each iteration. If true, the loop continues; if false, the loop stops.
  3. Iteration: Updates the loop counter after each iteration.

Syntax

for (initialization; condition; iteration)
{
    // Code to be executed
}

Basic Example

Let’s start with a simple example to print numbers from 1 to 10.

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

Explanation

  • Initialization: int i = 1 sets the loop counter i to 1.
  • Condition: i <= 10 ensures the loop runs as long as i is less than or equal to 10.
  • Iteration: i++ increments the loop counter by 1 after each iteration.

Iterating Through an Array

The for loop is commonly used to iterate through arrays. Here’s an example:

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

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine("Element at index " + i + ": " + numbers[i]);
}

Explanation

  • The loop runs from i = 0 to i < numbers.Length, covering all elements in the array.
  • numbers[i] accesses the element at the current index.

Explanation

  • The outer loop runs from i = 1 to i <= 10.
  • The inner loop runs from j = 1 to j <= 10.
  • The product of i and j is printed, formatted to align neatly.

Are you looking for Live Training in C#?

The upcoming batch for C#.NET is sceduled.

Book Your Seat Now.

Using the Break Statement

The break statement can be used to exit the loop prematurely.

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

Explanation

  • The loop prints numbers from 1 to 4.
  • When i equals 5, the break statement exits the loop.

Using the Continue Statement

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0)
    {
        continue;
    }
    Console.WriteLine(i);
}

The continue statement skips the current iteration and proceeds with the next one.

Explanation

  • The loop prints only odd numbers between 1 and 10.
  • When i is even, the continue statement skips the rest of the loop body.

For Loop with Collections

Besides arrays, you can use for loops with other collections like List<T>.

using System.Collections.Generic;

List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

for (int i = 0; i < fruits.Count; i++)
{
    Console.WriteLine("Fruit at index " + i + ": " + fruits[i]);
}

Explanation

  • The loop iterates through the List<string> collection fruits.
  • fruits[i] accesses the element at the current index.

Example Code

Here’s the complete example code that you can try in your C# environment:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Basic for loop
        for (int i = 1; i <= 10; i++)
        {
            Console.WriteLine(i);
        }

        // Iterating through an array
        int[] numbers = { 10, 20, 30, 40, 50 };
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine("Element at index " + i + ": " + numbers[i]);
        }

        // Nested for loops (Multiplication table)
        for (int i = 1; i <= 10; i++)
        {
            for (int j = 1; j <= 10; j++)
            {
                Console.Write((i * j).ToString().PadLeft(4));
            }
            Console.WriteLine();
        }

        // Break statement
        for (int i = 1; i <= 10; i++)
        {
            if (i == 5)
            {
                break;
            }
            Console.WriteLine(i);
        }

        // Continue statement
        for (int i = 1; i <= 10; i++)
        {
            if (i % 2 == 0)
            {
                continue;
            }
            Console.WriteLine(i);
        }

        // For loop with List
        List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
        for (int i = 0; i < fruits.Count; i++)
        {
            Console.WriteLine("Fruit at index " + i + ": " + fruits[i]);
        }
    }
}

If you found this blog post helpful, feel free to share it with your fellow developers or leave a comment below with your thoughts and questions.

Are you looking for Live Training in C#?

The upcoming batch for C#.NET is sceduled.

Book Your Seat Now.

Conclusion

The for loop is a powerful and versatile control structure in C#. It allows you to perform repeated tasks efficiently, making it an indispensable tool for any programmer. By understanding and utilizing the for loop, you can handle a wide range of programming scenarios, from simple iterations to complex nested loops.