![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements