C# foreach loop: In this tutorial, we will learn about foreach loops (an alternative to for loop) and how to use them with arrays and collections.

The foreach statement in C# iterates through a collection of items like an array or rundown, The foreach body should be enclosed in {} braces unless if it comprises of a single statement.

C# gives a simple to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to emphasize through the items of arrays/collections. The foreach loop iterates through each item, consequently called foreach circle.

Before moving forward with foreach loop, visit:

C# for loop

• C# arrays

• C# collections


Syntax of foreach loop

foreach (element in iterable-item)
{
    // body of foreach loop
}

Here iterable-item can be an array or a class of collection.


How foreach loop works?

The in watchword used alongside foreach loop is used to iterate over the iterable-item. The in watchword chooses an item from the iterable-item on each iteration and store it in the variable element.

On first iteration, the first item of iterable-item is put away in element. On second iteration, the second element is chosen, etc.

The occasions the foreach loop will execute is equivalent to the number of elements in the array or collection.

Here is an illustration of iterating through an array using the for loop:


Example 1: Printing array using for loop

using System;
 
namespace Loop
{
    class ForLoop
    {
        public static void Main(string[] args)
        {
            char[] myArray = {'H','e','l','l','o'};
 
            for(int i = 0; i < myArray.Length; i++)
            {
                Console.WriteLine(myArray[i]);
            }
        }
    }
}

A similar task should be possible using the foreach loop.

Example 2: Printing array using foreach loop

using System;
 
namespace Loop
{
    class ForEachLoop
    {
        public static void Main(string[] args)
        {
            char[] myArray = {'H','e','l','l','o'};
 
            foreach(char ch in myArray)
            {
                Console.WriteLine(ch);
            }
        }
    }
}

At the point when we run the both program, the output will be:

H
e
l
l
o

In the above program, the foreach loop emphasizes over the array, myArray. On first iteration, the first element for example myArray[0] is chosen and put away in ch.

Essentially on the last emphasis, the last element for example myArray[4] is chosen. Inside the body of loop, the worth of ch is printed.

At the point when we look at the two programs, the program that uses foreach loop is more readable and straightforward. This is because of its basic and expressive syntax.

Thus, foreach loop is liked over for loop when working with arrays and collections.


Example 3: Traversing an array of gender using foreach loop

This program computes the number of male and female candidates.

using System;
 
namespace Loop
{
    class ForEachLoop
    {
        public static void Main(string[] args)
        {
            char[] gender = {'m','f','m','m','m','f','f','m','m','f'};
            int male = 0, female = 0;
            foreach (char g in gender)  
            {
                if (g == 'm')
                        male++;
                else if (g =='f')
                        female++;
            }
            Console.WriteLine("Number of male = {0}", male);
            Console.WriteLine("Number of female = {0}", female);
        }
    }
}

At the point when we run the program, the output will be:

Number of male = 6
Number of female = 4

Example 4: foreach loop with List (Collection)

This program computes the sum of elements in a List.

using System;
using System.Collections.Generic;
 
namespace Loop
{
    class ForEachLoop
    {
        public static void Main(string[] args)
        {
            var numbers = new List() {5,-8,3,14,9,17,0,4};
            int sum = 0;
 
            foreach(int number in numbers)
            {
                sum += number;
            }
            Console.WriteLine("Sum = {0}", sum);
        }
    }
}

At the point when we run the program, the output will be:

Sum = 44

In this program, foreach loop is used to traverse through a collection. Traversing a collection is like to traversing through an array.

The first element of collection is chosen on the first iteration, second element on second iteration, etc till the last element.


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.


0 Comments

Leave a Reply

Avatar placeholder