Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you loop through a C# array?
To loop through an array in C#, you can use several loop types including for, foreach, while, and do...while loops. Each loop provides different ways to iterate through array elements and access their values.
The most commonly used loops for arrays are the for loop (when you need index access) and the foreach loop (when you only need element values).
Syntax
Following is the syntax for different loop types with arrays −
// for loop
for (int i = 0; i < array.Length; i++) {
// access array[i]
}
// foreach loop
foreach (dataType element in array) {
// access element directly
}
// while loop
int i = 0;
while (i < array.Length) {
// access array[i]
i++;
}
Using for Loop
The for loop is ideal when you need both the index and the element value −
using System;
class MyArray {
static void Main(string[] args) {
int[] n = new int[10];
int i, j;
for (i = 0; i < 10; i++) {
n[i] = i + 10;
}
for (j = 0; j < 10; j++) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
}
}
The output of the above code is −
Element[0] = 10 Element[1] = 11 Element[2] = 12 Element[3] = 13 Element[4] = 14 Element[5] = 15 Element[6] = 16 Element[7] = 17 Element[8] = 18 Element[9] = 19
Using foreach Loop
The foreach loop is simpler when you only need to read element values without requiring the index −
using System;
class Program {
static void Main(string[] args) {
string[] fruits = {"Apple", "Banana", "Orange", "Mango"};
Console.WriteLine("Fruits in the array:");
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
}
}
The output of the above code is −
Fruits in the array: Apple Banana Orange Mango
Using while Loop
The while loop provides more control over the iteration process −
using System;
class Program {
static void Main(string[] args) {
double[] numbers = {1.5, 2.7, 3.9, 4.2, 5.8};
int i = 0;
while (i < numbers.Length) {
Console.WriteLine("Number at index {0}: {1}", i, numbers[i]);
i++;
}
}
}
The output of the above code is −
Number at index 0: 1.5 Number at index 1: 2.7 Number at index 2: 3.9 Number at index 3: 4.2 Number at index 4: 5.8
Comparison of Loop Types
| Loop Type | Best Used When | Index Access |
|---|---|---|
for |
Need index or want to modify array elements | Yes |
foreach |
Only reading values, cleaner syntax | No |
while |
Complex iteration conditions | Yes |
Conclusion
C# provides multiple ways to loop through arrays. Use for loops when you need index access, foreach loops for simple value iteration, and while loops for complex iteration logic. The foreach loop is generally preferred for read-only operations due to its cleaner syntax.
