Loops are fundamental control structures in programming that allow you to execute a block of code multiple times. In C#, there are several types of loops, each suited for different scenarios. This section will cover the following types of loops:

  1. for loop
  2. while loop
  3. do-while loop
  4. foreach loop

  1. for Loop

The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.

Syntax

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

Example

using System;

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

Explanation

  • Initialization: int i = 0 sets the starting point.
  • Condition: i < 5 checks if the loop should continue.
  • Increment/Decrement: i++ updates the loop variable.

Exercise

Write a for loop that prints the numbers from 1 to 10.

using System;

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

  1. while Loop

The while loop is used when you want to execute a block of code as long as a specified condition is true.

Syntax

while (condition)
{
    // Code to be executed
}

Example

using System;

class Program
{
    static void Main()
    {
        int i = 0;
        while (i < 5)
        {
            Console.WriteLine("Iteration: " + i);
            i++;
        }
    }
}

Explanation

  • Condition: i < 5 checks if the loop should continue.
  • Code Block: Executes as long as the condition is true.

Exercise

Write a while loop that prints the numbers from 1 to 10.

using System;

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

  1. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once.

Syntax

do
{
    // Code to be executed
} while (condition);

Example

using System;

class Program
{
    static void Main()
    {
        int i = 0;
        do
        {
            Console.WriteLine("Iteration: " + i);
            i++;
        } while (i < 5);
    }
}

Explanation

  • Code Block: Executes once before the condition is checked.
  • Condition: i < 5 checks if the loop should continue.

Exercise

Write a do-while loop that prints the numbers from 1 to 10.

using System;

class Program
{
    static void Main()
    {
        int i = 1;
        do
        {
            Console.WriteLine(i);
            i++;
        } while (i <= 10);
    }
}

  1. foreach Loop

The foreach loop is used to iterate over a collection or an array.

Syntax

foreach (type variable in collection)
{
    // Code to be executed
}

Example

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        foreach (int number in numbers)
        {
            Console.WriteLine("Number: " + number);
        }
    }
}

Explanation

  • Collection: numbers is the array being iterated over.
  • Variable: number represents the current element in the array.

Exercise

Write a foreach loop that prints each character in the string "Hello, World!".

using System;

class Program
{
    static void Main()
    {
        string message = "Hello, World!";
        foreach (char c in message)
        {
            Console.WriteLine(c);
        }
    }
}

Common Mistakes and Tips

  • Infinite Loops: Ensure that the loop condition will eventually become false. For example, forgetting to increment the loop variable in a while loop can cause an infinite loop.
  • Off-by-One Errors: Be careful with the loop boundaries. For example, using i <= 5 instead of i < 5 in a for loop can lead to an extra iteration.
  • Collection Modification: Avoid modifying a collection while iterating over it with a foreach loop, as it can cause runtime exceptions.

Conclusion

In this section, you learned about the different types of loops in C# and how to use them. Loops are essential for performing repetitive tasks efficiently. Practice the exercises provided to reinforce your understanding and prepare for more complex programming challenges. Next, we will explore switch statements, which provide a way to handle multiple conditions more elegantly than using multiple if-else statements.

© Copyright 2024. All rights reserved