Friday 17 August 2018

C#: for-each loop

‘for-each’ loop is used to iterate over a collection of elements.

Syntax
foreach(datatype variable in collection){

}

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        int[] primeNumbers = new int[10];

        primeNumbers[0] = 2;
        primeNumbers[1] = 3;
        primeNumbers[2] = 5;
        primeNumbers[3] = 7;
        primeNumbers[4] = 11;
        primeNumbers[5] = 13;
        
        foreach(int num in primeNumbers)
        {
            Console.WriteLine(num);
        }
    }
}

Output
2
3
5
7
11
13
0
0
0
0



Previous                                                 Next                                                 Home

No comments:

Post a Comment