Looping in a programming language is a way to execute a statement or a set of statements multiple numbers of times depending on the result of a condition to be evaluated. The resulting condition should be true to execute statements within loops. 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.
It is necessary to enclose the statements of foreach loop in curly braces {}.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.In the loop body, you can use the loop variable you created rather than using an indexed array element.
using System; class Program
{
static void Main(string[] args)
{
Console.WriteLine("foreach loop Sample!");
int[] oddArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 }; foreach (int num in oddArray)
{
Console.WriteLine(num);
}
Console.ReadKey();
}
}
Foreach in Array
Here is another example of using a foreach, in loop. The code snippet in Listing 6 creates an array of strings, reads and display each string one at a time.
/ Array of authors -
string string[] authorList = new string[] { "Mahesh Chand", "Raj Kumar", "Naveen Sharma", "Allen O'neill", "Dave McCarter" };
// Loop through array and read all authors foreach (string author in authorList )
{
Console.WriteLine(author);
}