The foreach loop is similar to the for loop with a slight difference. The foreach loop allows you to iterate through arrays and collections(collections are similar to arrays but unlike arrays,they can store different types of objects together).Unlike the for loop, the foreach loop does not check any condition. The foreach loop simply goes through the items or elements of an array of collection and executes a set of statements for every element. The foreach loop automatically terminates after the execution of statements for the last element of the array or collection.
The syntax of the foreach loop is as follow:
foreach(Data_Type Item_Variable in Collection_Name)
{
//statements
}
In the Preceding syntax,
foreach :Refers to the foreach keyword that indicates a foreach loop.
Data_Type : Refers to the data type of the items of the array or collection
Item_Variable: Refers to an item or element of the array or collection
In : Refers to the in keyword
Collection_Name: Refers to an array or collection
statements: Refers to the set of statements that is executed for every item in the array or collection.
using System;
public class Program
{
public static void Main()
{
string[] days={"Sunday","Monday","Tuesday","Wendnesday",
"Thursday","Firday","Saturday"};
Console.WriteLine("Days of Week :");
foreach(string day in days)
{
Console.WriteLine(day);
}
Console.ReadLine();
}
}
We first create an array of string type, days, which the names of the days in a week. After this,we use a foreach loop to display the array elements on the colsole.In the foreach loop, the string variable, day represents a single element of the days array.
8.Press the F5 keyboard to run the applications.
Comments