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 to iterate efficiently through an array of integers of unknown size in C#
To iterate efficiently through an array of integers of unknown size in C#, there are several approaches available. The key is to use the array's Length property or built-in iteration methods that automatically handle the array size.
Syntax
Following is the syntax for basic array iteration using a for loop −
for (int i = 0; i < arr.Length; i++) {
// access arr[i]
}
Following is the syntax for using foreach loop −
foreach (int element in arr) {
// access element directly
}
Using for Loop with Length Property
The traditional approach uses a for loop with the array's Length property. This method provides index access and is efficient for large arrays −
using System;
public class Program {
public static void Main() {
int[] arr = new int[] { 5, 7, 2, 4, 1 };
Console.WriteLine("Length: " + arr.Length);
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine("Index " + i + ": " + arr[i]);
}
}
}
The output of the above code is −
Length: 5 Index 0: 5 Index 1: 7 Index 2: 2 Index 3: 4 Index 4: 1
Using foreach Loop
The foreach loop is more concise and eliminates the need for index management. It's the preferred method when you don't need the index −
using System;
public class Program {
public static void Main() {
int[] arr = new int[] { 15, 25, 35, 45, 55 };
Console.WriteLine("Array elements using foreach:");
foreach (int element in arr) {
Console.WriteLine(element);
}
}
}
The output of the above code is −
Array elements using foreach: 15 25 35 45 55
Using while Loop
A while loop provides another alternative when you need more control over the iteration process −
using System;
public class Program {
public static void Main() {
int[] arr = new int[] { 10, 20, 30, 40, 50 };
int index = 0;
Console.WriteLine("Array elements using while loop:");
while (index < arr.Length) {
Console.WriteLine("Element at position " + index + ": " + arr[index]);
index++;
}
}
}
The output of the above code is −
Array elements using while loop: Element at position 0: 10 Element at position 1: 20 Element at position 2: 30 Element at position 3: 40 Element at position 4: 50
Comparison of Iteration Methods
| Method | Index Access | Performance | Best Use Case |
|---|---|---|---|
| for loop | Yes | Fast | When you need index or reverse iteration |
| foreach loop | No | Fast | Simple iteration without index |
| while loop | Yes | Fast | Complex iteration conditions |
Conclusion
Iterating through arrays of unknown size in C# is straightforward using the Length property. The foreach loop is the most concise for simple iterations, while for loops provide index access when needed. All methods automatically adapt to any array size without requiring manual size specification.
