- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Iterating C# StringBuilder in a foreach loop
- How do you use ‘foreach’ statement for accessing array elements in C#
- How do you use a ‘for loop’ for accessing array elements in C#?
- How do we use foreach statement to loop through the elements of an array in C#?
- Iterating over array in Java
- How do you loop through a C# array?
- foreach Loop in C#
- How to use PowerShell break statement in foreach loop?
- How to use PSCustomObject in PowerShell foreach parallel loop?
- How to use the foreach loop parallelly in PowerShell?
- How to use for each loop through an array in Java?
- How do you throw an Exception without breaking a for loop in java?
- How do you empty an array in C#?
- How to use for...in statement to loop through an Array in JavaScript?
- C# program to iterate over a string array with for loop

Advertisements