Algorithm


In C#, the foreach loop is used to iterate over elements in a collection, such as an array, list, or other enumerable types. The syntax for the foreach loop is straightforward and provides a concise way to iterate through elements without the need for explicit indexing.

 

Code Examples

#1 Printing array using for loop in C# Programming

Code - C# Programming

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]);
            }
        }
    }
}
Copy The Code & Try With Live Editor

#2 Printing array using foreach loop in C# Program

Code - C# Programming

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);
            }
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
H
e
l
l
o

#3 Traversing an array of gender using foreach loop in C# Programming

Code - C# Programming

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);
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Number of male = 6
Number of female = 4

#4 foreach loop with List (Collection) in C# Programming

Code - C# Programming

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

Output

x
+
cmd
Sum = 44
Advertisements

Demonstration


C# Programming foreach loop