How do we use foreach statement to loop through the elements of an array in C#?


A foreach loop is used to execute a statement or a group of statements for each element in an array or collection.

It is similar to for Loop; however, the loop is executed for each element in an array or group. Therefoe, the index does not exist in it.

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

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements