All Type Coding

Search Here

foreach loop in C#?

foreach loop
foreach loop is a different kind of looping constructs in C# programming that doesn’t includes initialization, termination and increment/decrement characteristics. It uses collection to take value one by one and then processes them or A program iterates over a collection. The index of each element is not needed. Only the elements are needed. With foreach we access just the elements
syntax:
 foreach (string name in arr)
 {
 }

For Example

using System;

namespace foreach_loop
{
  class Program
   {
     static void Main(string[] args)
      {
        string[] arr = new string[5]; // declaring array

        //Storing value in array element
        arr[0] = "A";
        arr[1] = "B";
        arr[2] = "C";
        arr[3] = "D";
        arr[4] = "E";

        //retrieving value using foreach loop
        foreach (string name in arr)
         {
           Console.WriteLine("Hello " + name);
         }
        Console.ReadLine();
      }
   }
}


Output is:



No comments :

Post a Comment