C# for Loop

Introduction

The for loop in C# is a control flow statement that allows you to execute a block of code a specific number of times. It is particularly useful when the number of iterations is known beforehand. The for loop provides a compact way to iterate over a range of values.

Syntax

for (initialization; condition; iteration)
{
    // Code to execute on each loop iteration
}

Components of a for Loop

  1. Initialization: This section initializes the loop counter and is executed only once at the beginning of the loop.
  2. Condition: This section is evaluated before each iteration of the loop. If the condition is true, the loop body executes. If the condition is false, the loop terminates.
  3. Iteration: This section updates the loop counter after each iteration of the loop body.

Example

Here’s a complete example demonstrating the use of the for loop in C#:

using System;

namespace ForLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Using a for loop to print numbers from 1 to 10
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("Number: " + i);
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Program finished.

Explanation

  1. Initialization: int i = 1; initializes the loop counter i to 1.
  2. Condition: i <= 10; checks if i is less than or equal to 10. If true, the loop body executes.
  3. Iteration: i++ increments the loop counter by 1 after each iteration.

Example: Sum of First N Natural Numbers

This example calculates the sum of the first 10 natural numbers using a for loop:

using System;

namespace SumOfNaturalNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;

            // Using a for loop to calculate the sum of first 10 natural numbers
            for (int i = 1; i <= 10; i++)
            {
                sum += i;
            }

            Console.WriteLine("Sum of first 10 natural numbers: " + sum);

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Sum of first 10 natural numbers: 55
Program finished.

Explanation

  1. Initialization: int sum = 0; initializes the sum variable to 0.
  2. Condition: i <= 10; ensures the loop runs 10 times.
  3. Iteration: sum += i; adds the value of i to the sum in each iteration.

Example: Iterating Through an Array

This example demonstrates how to use a for loop to iterate through an array of strings:

using System;

namespace ArrayIteration
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

            // Using a for loop to iterate through the array
            for (int i = 0; i < fruits.Length; i++)
            {
                Console.WriteLine("Fruit: " + fruits[i]);
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Fruit: Apple
Fruit: Banana
Fruit: Cherry
Fruit: Date
Fruit: Elderberry
Program finished.

Explanation

  1. Initialization: int i = 0; initializes the loop counter i to 0.
  2. Condition: i < fruits.Length; ensures the loop runs as long as i is less than the length of the array.
  3. Iteration: Console.WriteLine("Fruit: " + fruits[i]); prints each element of the array.

Example: Nested for Loop

This example demonstrates the use of a nested for loop to print a multiplication table:

using System;

namespace NestedForLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Using nested for loops to print a multiplication table
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    Console.Write(i * j + "\t");
                }
                Console.WriteLine();
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

1	2	3	4	5
2	4	6	8	10
3	6	9	12	15
4	8	12	16	20
5	10	15	20	25
Program finished.

Explanation

  1. Outer Loop Initialization: int i = 1; initializes the outer loop counter i to 1.
  2. Outer Loop Condition: i <= 5; ensures the outer loop runs 5 times.
  3. Inner Loop Initialization: int j = 1; initializes the inner loop counter j to 1.
  4. Inner Loop Condition: j <= 5; ensures the inner loop runs 5 times.
  5. Multiplication and Printing: Console.Write(i * j + "\t"); prints the product of i and j followed by a tab space.
  6. Line Break: Console.WriteLine(); adds a line break after each row.

Conclusion

The for loop is used for repeating a block of code a specific number of times. It is versatile and can be used for various tasks such as iterating through arrays, calculating sums, and generating patterns. By mastering the for loop, you can write more efficient and concise C# programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top