How to Iterate Over Array in C#: Simple Syntax and Examples
In C#, you can iterate over an array using a
for loop or a foreach loop. The for loop uses an index to access each element, while foreach directly accesses each element in the array.Syntax
There are two common ways to loop through an array in C#:
- for loop: Uses an index to access elements by position.
- foreach loop: Accesses each element directly without an index.
This makes it easy to choose based on whether you need the index or just the values.
csharp
int[] numbers = {1, 2, 3, 4, 5}; // for loop syntax for (int i = 0; i < numbers.Length; i++) { // Access element by index int number = numbers[i]; } // foreach loop syntax foreach (int number in numbers) { // Access element directly }
Example
This example shows how to print each number in an array using both for and foreach loops.
csharp
using System; class Program { static void Main() { int[] numbers = {10, 20, 30, 40, 50}; Console.WriteLine("Using for loop:"); for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } Console.WriteLine("Using foreach loop:"); foreach (int number in numbers) { Console.WriteLine(number); } } }
Output
Using for loop:
10
20
30
40
50
Using foreach loop:
10
20
30
40
50
Common Pitfalls
Some common mistakes when iterating over arrays in C# include:
- Using a
forloop with an incorrect condition, causing out-of-range errors. - Modifying the collection inside a
foreachloop, which is not allowed. - Confusing the index variable with the element value.
csharp
int[] arr = {1, 2, 3}; // Wrong: loop condition causes out-of-range error for (int i = 0; i <= arr.Length; i++) { Console.WriteLine(arr[i]); // Error when i == arr.Length } // Correct: for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); }
Quick Reference
Here is a quick summary of how to iterate over arrays in C#:
| Method | Usage | When to Use |
|---|---|---|
| for loop | for (int i = 0; i < array.Length; i++) | When you need the index or want to modify elements by position |
| foreach loop | foreach (var item in array) | When you only need to read elements without modifying the array |
Key Takeaways
Use a for loop to iterate with an index over an array in C#.
Use a foreach loop to iterate directly over elements without needing the index.
Always ensure the for loop condition uses < array.Length to avoid errors.
Do not modify the array inside a foreach loop to prevent runtime exceptions.
Choose the loop type based on whether you need the element index or just the values.