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.
*/
Differences Between For and Foreach Loops

The main difference between for and foreach loops is that for loops are index-based, allowing you to modify the loop variable and have more control over the iteration process. Foreach loops, on the other hand, are simpler to write but don't provide access to the index, making them more suitable for read-only iterations over collections.

While Loop in C#

While loops execute code continuously until a condition becomes false. Here's a simple example:

using System;

class Program
{
    static void Main()
    {
        int num = 0;
        // The loop keeps running until `num` is greater than or equal to 5
        while (num < 5)
        {
            Console.WriteLine(num); // prints numbers from 0 to 4
            // increase `num` by 1 each iteration
            num += 1;
        }
    }
}
/*
Prints:
0
1
2
3
4
*/

As you can see, before each iteration, C# checks the condition (num < 5). If it's true, the code block runs; otherwise, C# exits the loop.

Looping Over Collections

C# loops can directly work with collections, making it easy to handle elements of an array or string.

For instance, consider looping over an array:

using System;

class Program
{
    static void Main()
    {
        // array of fruits
        string[] fruits = { "apple", "banana", "cherry" };
        // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array
        for (int i = 0; i < fruits.Length; i++)
        {
            Console.WriteLine(fruits[i]); // prints each fruit using the index `i`
        }
    }
}
/*
Prints:
apple
banana
cherry
*/

And, looping over a string:

using System;

class Program
{
    static void Main()
    {
        string word = "hello";
        // `letter` is each individual character in the `word`
        foreach (char letter in word)
        {
            Console.WriteLine(letter); // prints each letter in 'hello'
        }
    }
}
/*
Prints:
h
e
l
l
o
*/
Applications of Looping

Loops are integral to programming. They are used in various programming applications, such as summing numbers in an array or parsing text.

using System;

class Program
{
    static void Main()
    {
        // Array of numbers
        int[] numbers = { 1, 2, 3, 4, 5 };
        int total = 0;
        // The `for` loop initializes an index (`i`) and runs from 0 to the length of the array
        for (int i = 0; i < numbers.Length; i++)
        {
            total += numbers[i]; // add each number in the array using the index `i`
        }
        Console.WriteLine(total); // prints the total sum
    }
}
/*
Prints:
15
*/
using System;

class Program
{
    static void Main()
    {
        // string
        string text = "hello";
        int vowel_count = 0;
        // `letter` is each character in `text`
        foreach (char letter in text)
        {
            // If a vowel letter is found, increment the count
            if ("aeiou".Contains(letter))
            {
                vowel_count += 1;
            }
        }
        Console.WriteLine(vowel_count); // prints the count of vowels
    }
}
/*
Prints:
2
*/
Lesson Summary and Practice

Well done on getting a grasp of C# loops! We brushed up on looping fundamentals, C#'s for and while loops, and how to loop over collections. Now, it's time for some essential practice exercises to cement your learning. The more problems you solve, the more adept you become. Onward, we continue on the programming voyage!

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