Loops in C#

Topic Overview and Actualization

Hello, Explorer! Today, we will revisit C# loops, essential tools that simplify repetitive tasks. Think of loops like a marathon of TV series episodes. We will venture into the C# looping universe and acquire hands-on experience by applying loops to collections like arrays and strings.

Understanding Looping

Have you ever experienced repeating a favorite song on a loop? That's what loops are all about in programming too. For example, you can print greetings for an array of friends using a for loop:

For Loop in C#

In C#, a for loop works with any sequence, like arrays or strings. Let's print greetings for an array of friends using a for loop:

using System;

class Program
{
    static void Main()
    {
        string[] friends = { "Alice", "Bob", "Charlie", "Daniel" };
        // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array
        for (int i = 0; i < friends.Length; i++)
        {
            // Access each element using the index `i`
            Console.WriteLine($"Hello, {friends[i]}! Nice to meet you.");
        }
    }
}
/*
Prints:
Hello, Alice! Nice to meet you.
Hello, Bob! Nice to meet you.
Hello, Charlie! Nice to meet you.
Hello, Daniel! Nice to meet you.
*/

Each loop iteration updates the variable (i) to the next sequence value before executing the code block. This is useful when you need the index for accessing elements in an array.

Foreach Loop in C#

A foreach loop is used to iterate over elements in a collection without the need for an index. It simplifies the process of accessing each element without needing to manage the loop counter manually. Here's an example:

using System;

class Program
{
    static void Main()
    {
        string[] friends = { "Alice", "Bob", "Charlie", "Daniel" };
        // `friend` is the loop variable, taking each name in the `friends` array
        foreach (string friend in friends)
        {
            // for each `friend`, this line is executed
            Console.WriteLine($"Hello, {friend}! Nice to meet you.");
        }
    }
}
/*
Prints:
Hello, Alice! Nice to meet you.
Hello, Bob! Nice to meet you.
Hello, Charlie! Nice to meet you.
Hello, Daniel! Nice to meet you.
*/
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal