

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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
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 Questions & Answers
- How to loop through all the elements of an array in C#?
- How to use for...in statement to loop through an Array in JavaScript?
- How do you use ‘foreach’ statement for accessing array elements in C#
- How to use PowerShell break statement in foreach loop?
- How do you use ‘foreach’ loop for iterating over an array in C#?
- How do we use continue statement in a while loop in C#?
- How do we use a break statement in while loop in C#?
- How do we loop through array of arrays containing objects in JavaScript?
- How do you loop through a C# array?
- How to use for each loop through an array in Java?
- How to loop through an array in Java?
- How to use the foreach loop parallelly in PowerShell?
- Loop through an array in Java
- foreach Loop in C#
- How to use PSCustomObject in PowerShell foreach parallel loop?
Advertisements