For Each Loop, For Loop के समान है; हालांकि, Loop Array या Group में प्रत्येक Element के लिए Execute होता है। इसलिए, Index Foreach Loop में Exist नहीं करता।
आइए Bubble Sort का एक Example देखते हैं, जिसमें Elements Sort करने के बाद, हम Foreach Loop का उपयोग करके Elements Display करेंगे।
foreach (int p in arr) Console.Write(p + " ");
निम्न Complete Example है।
Example
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