How do you use ‘foreach’ loop for iterating over an array in C#?



The for each loop similar to the for loop; however, the loop is executed for each element in an array or group. Therefore, the index does not exist in foreach loop.

Let us see an example of Bubble Sort, wherein after sorting the elements, we will display the elements using the foreach loop.

foreach (int p in arr)
Console.Write(p + " ");

The following is the complete example.

Example

 Live Demo

using System;
namespace BubbleSort {
   class MySort {
      static void Main(string[] args) {
         int[] arr = { 78, 55, 45, 98, 13 };
         int temp;
         for (int j = 0; j <= arr.Length - 2; j++) {
            for (int i = 0; i <= arr.Length - 2; i++) {
               if (arr[i] > arr[i + 1]) {
                  temp= arr[i + 1];
                  arr[i + 1] = arr[i];
                  arr[i] = temp;
               }
            }
         }
         Console.WriteLine("Sorted:");
         foreach (int p in arr)
         Console.Write(p + " ");
         Console.Read();
      }
   }
}

Output

Sorted:
13 45 55 78 98
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements