
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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 Articles
- How do you use ‘foreach’ statement for accessing array elements in C#
- How do you use ‘foreach’ loop for iterating over an array in C#?
- How to use for...in statement to loop through an Array in JavaScript?
- How to use PowerShell break statement in foreach loop?
- How to loop through all the elements of 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 to use for each loop through an array in Java?
- How do you loop through a C# array?
- How do you use a ‘for loop’ for accessing array elements in C#?
- How to use the foreach loop parallelly in PowerShell?
- How to loop through an array in Java?
- How to use PSCustomObject in PowerShell foreach parallel loop?
- How to use for and foreach loop in Golang?

Advertisements