foreach Loop in C# programming

foreach loop is extension of For Loop. This loop executes block of statements for each member of an array. Indexes of elements are not needed for this loop, just the current element of array is available inside the loop.

Syntax for foreach Loop is:

for (datatype variable_name in array_name)
{
    statements;
}

Here, datatype indicates the data type of the elements of the array. variable_name is the name for variable where elements of array will be stored. in is a keyword that points to the array and array_name is the name of array.

Example 1: C# example of foreach Loop

C# program to read vowels from an array of characters and display it using foreach loop.

using System;
namespace loop
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] vowels = { 'a', 'e', 'i', 'o', 'u'};
            foreach (char v in vowels)
            {
                Console.WriteLine(v);
            }
            Console.ReadLine();
        }
    }
}

In above program, vowels are stored in a variable vowels. The foreach statement is used to read every value stored in the array one by one. Then the statement inside the loop, Console.WriteLine(v);, prints current value from array. The loop runs until all the values in the array have been printed out.

Output:

a
e
i
o
u