Foreach Loop in C#

0
Foreach Loop in C#:-


It is the special loop in C# that is used to display the array elements specially, It is the modified form of for loop.

Syntax of foreach

foreach(var in arrayvar1)
{
         Statements;
}

Example of Foreach Loop Based Program in C#:-

 class ObjectArr
    {
        static void Main()
        {
           // object [] arr = {"C","CPP",1200,12.34F,true,'a' };
            int[] arr = { 12, 23, 11, 45, 67 };
            foreach (int a in arr)
            {
                Console.WriteLine(a);
            }
}



Another Example of Foreach Loop to Display Elements?

using System;
class ForeachDemo
{
   static void Main()
   {
        int [] arr = {12,23,47,89,11,77};
        foreach(int k in arr)
        {
              Console.WriteLine(k);
        }
       object [] o = {"C",123,"C++",true,12.34F};
       foreach(object o1 in o)
       {
          Console.WriteLine(o1);
       }

   }

}



Nested Foreach Loop:-

We can create more than one foreach loop using nested sequence, it is used to display multidimensional array or Jagged Array.



Example of Multidimensional Foreach Loop

using System;
class ForeachDemo
{
   static void Main()
   {
     int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
     foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}
    
   }

}




     
Tags

Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)