s

C# for each Loop edit button Edit

author
Rakesh Kumar Sutar | calendar 12 January 2021 | 3356

Introduction

The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.

Syntax

foreach(data_type var_name in collection_variable)
{
     // statements to be executed
}

Example - foreach Loop

using System;

namespace Hello_world
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Print array:");

            // creating an array 
            String[] a_array = new string[] { "Sunday", "Monday","Tuesday","Wednesday","Thuresday","Friday","Saturday" };

            // foreach loop begin 
            // it will run till the 
            // last element of the array 
            foreach (String items in a_array)
            {
                Console.WriteLine("   " items);
            }
        }
    }
}

Output