C# -

Loops

Loops in C# are used to execute a block of code repeatedly until a specified condition is met. They are essential for tasks that require repetitive actions. This tutorial covers various types of loops in C#, including `for`, `foreach`, `while`, `do-while` loops, and `List.ForEach`.


Types of Loops

Loop Type Description
for Executes a block of code a specified number of times, based on a counter variable.
foreach Iterates through each element in a collection or array.
while Executes a block of code as long as a specified condition is true.
do-while Executes a block of code at least once, and then repeatedly executes the block as long as a specified condition is true.
List.ForEach Executes a specified action on each element of a list.

1. for Loop

The for loop executes a block of code a specified number of times, based on a counter variable.

Basic Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine($"Iteration: {i}");
        }
    }
}
        
    
Advanced Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0, j = 10; i < j; i++, j--)
        {
            Console.WriteLine($"i: {i}, j: {j}");
        }

        int[] numbers = { 1, 2, 3, 4, 5 };
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine($"Number: {numbers[i]}");
        }
    }
}
        
    

2. foreach Loop

The foreach loop iterates through each element in a collection or array.

Basic Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        string[] names = { "Alice", "Bob", "Charlie" };
        foreach (var name in names)
        {
            Console.WriteLine($"Name: {name}");
        }
    }
}
        
    
Advanced Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        var people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        foreach (var person in people)
        {
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
        
    

3. while Loop

The while loop executes a block of code as long as a specified condition is true.

Basic Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        while (counter < 5)
        {
            Console.WriteLine($"Counter: {counter}");
            counter++;
        }
    }
}
        
    
Advanced Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        int number = 10;
        while (number >= 0)
        {
            Console.WriteLine($"Number: {number}");
            number -= 2;
        }

        // Infinite loop with a break condition
        int sum = 0;
        while (true)
        {
            sum += 1;
            if (sum > 10)
                break;
        }
        Console.WriteLine($"Sum: {sum}");
    }
}
        
    

4. do-while Loop

The do-while loop executes a block of code at least once, and then repeatedly executes the block as long as a specified condition is true.

Basic Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        do
        {
            Console.WriteLine($"Counter: {counter}");
            counter++;
        } while (counter < 5);
    }
}
        
    
Advanced Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        int number;
        do
        {
            Console.WriteLine("Enter a number greater than 0:");
            number = int.Parse(Console.ReadLine());
        } while (number <= 0);

        Console.WriteLine($"You entered: {number}");
    }
}
        
    

5. List.ForEach

The List.ForEach method executes a specified action on each element of a list. This method is convenient and can be used for simple operations on each list element.

Basic Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        List<int> numbers = new() { 1, 2, 3, 4, 5 };
        numbers.ForEach(number => Console.WriteLine(number));
    }
}
        
    
Advanced Example:
        
            namespace LoopExamples;

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new()
        {
            new Person { Name = "Alice", Age = 30 },
            new Person { Name = "Bob", Age = 25 },
            new Person { Name = "Charlie", Age = 35 }
        };

        people.ForEach(person =>
        {
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
            person.Age += 1; // Modifying the elements within the loop
        });

        Console.WriteLine("After modification:");
        people.ForEach(person => Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"));
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
        
    

Best Practices


When to Use Each Loop Type

for Loop: Use when you need to iterate a specific number of times or when you need access to the index of the current iteration.

foreach Loop: Use when you need to iterate over all elements in a collection or array and do not need access to the index of the current element.

while Loop: Use when the number of iterations is not known before entering the loop and the loop should continue as long as a condition is true.

do-while Loop: Use when you need to ensure the loop executes at least once, regardless of the condition.

List.ForEach: Use when you need to perform simple operations on each element of a list. It is a concise and readable way to apply an action to each element.


Limitations of Loops


Conclusion

Understanding and using loops effectively is crucial for handling repetitive tasks in C#. This tutorial covered various types of loops, including for, foreach, while, do-while loops, and List.ForEach, along with best practices for using them.