C# Loop Through Arrays - Complete Guide
Introduction to Array Iteration
Looping through arrays is a fundamental operation in C# programming. Several constructs exist for traversing elements, each offering different levels of control and readability. The choice of loop often depends on whether you need index access, modification capabilities, or simply to read elements.
Mastering different iteration techniques helps you write efficient, clean, and maintainable code when working with arrays and collections.
For Loop Iteration
The traditional for loop offers full control over iteration. It allows index-based access, supports custom steps, reverse iteration, and modifications of elements in place.
using System;
namespace ForLoopArrayIteration
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
string[] names = { "Alice", "Bob", "Charlie", "Diana" };
Console.WriteLine("Numbers array:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Index {i}: {numbers[i]}");
}
Console.WriteLine("\nNames array (reverse):");
for (int i = names.Length - 1; i >= 0; i--)
{
Console.WriteLine($"Index {i}: {names[i]}");
}
Console.WriteLine("\nEvery second number:");
for (int i = 0; i < numbers.Length; i += 2)
{
Console.WriteLine($"Index {i}: {numbers[i]}");
}
Console.WriteLine("\nFirst three names:");
for (int i = 0; i < 3 && i < names.Length; i++)
{
Console.WriteLine($"Index {i}: {names[i]}");
}
int[] values = { 1, 2, 3, 4, 5 };
Console.WriteLine($"\nOriginal values: {string.Join(", ", values)}");
for (int i = 0; i < values.Length; i++)
{
values[i] *= 2;
}
Console.WriteLine($"Modified values: {string.Join(", ", values)}");
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine("\n2D array with nested for loops:");
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write($"{matrix[row, col]} ");
}
Console.WriteLine();
}
}
}
}
Numbers array: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50 Names array (reverse): Index 3: Diana Index 2: Charlie Index 1: Bob Index 0: Alice Every second number: Index 0: 10 Index 2: 30 Index 4: 50 First three names: Index 0: Alice Index 1: Bob Index 2: Charlie Original values: 1, 2, 3, 4, 5 Modified values: 2, 4, 6, 8, 10 2D array with nested for loops: 1 2 3 4 5 6 7 8 9
Foreach Loop Iteration
The foreach loop offers a concise and readable way to traverse arrays. It is ideal for read-only operations where you do not need the index or to modify elements directly.
using System;
namespace ForeachArrayIteration
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
string[] names = { "Alice", "Bob", "Charlie", "Diana" };
Console.WriteLine("Numbers array:");
foreach (int number in numbers)
{
Console.WriteLine("Number: " + number);
}
Console.WriteLine("\nNames array:");
foreach (string name in names)
{
Console.WriteLine("Name: " + name);
}
Console.WriteLine("\nUsing var keyword:");
foreach (var number in numbers)
{
Console.WriteLine("Number: " + number);
}
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Console.WriteLine("\n2D array with foreach (flattened):");
foreach (int value in matrix)
{
Console.Write(value + " ");
}
Console.WriteLine();
int[][] jaggedArray = {
new int[] { 1, 2 },
new int[] { 3, 4, 5 },
new int[] { 6, 7, 8, 9 }
};
Console.WriteLine("\nJagged array with nested foreach:");
foreach (int[] innerArray in jaggedArray)
{
foreach (int value in innerArray)
{
Console.Write(value + " ");
}
Console.WriteLine();
}
int[] values = { 1, 2, 3, 4, 5 };
Console.WriteLine($"\nOriginal values: {string.Join(", ", values)}");
int sum = 0;
foreach (int value in values)
{
sum += value;
}
Console.WriteLine($"Sum of values: {sum}");
int max = int.MinValue;
foreach (int value in values)
{
if (value > max)
{
max = value;
}
}
Console.WriteLine($"Maximum value: {max}");
}
}
}
Numbers array: Number: 10 Number: 20 Number: 30 Number: 40 Number: 50 Names array: Name: Alice Name: Bob Name: Charlie Name: Diana Using var keyword: Number: 10 Number: 20 Number: 30 Number: 40 Number: 50 2D array with foreach (flattened): 1 2 3 4 5 6 7 8 9 Jagged array with nested foreach: 1 2 3 4 5 6 7 8 9 Original values: 1, 2, 3, 4, 5 Sum of values: 15 Maximum value: 5
Alternative Iteration Methods
Besides for and foreach loops, C# provides additional techniques for iterating arrays. These include built-in helpers, LINQ, while/do-while loops, ArraySegment, custom iterators, and modern features like Span
using System;
using System.Linq;
using System.Collections.Generic;
namespace AlternativeIterationMethods
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine("Using Array.ForEach:");
Array.ForEach(numbers, number => Console.WriteLine("Number: " + number));
Console.WriteLine("\nUsing LINQ (convert to list first):");
numbers.ToList().ForEach(number => Console.WriteLine("Number: " + number));
Console.WriteLine("\nUsing while loop:");
int index = 0;
while (index < numbers.Length)
{
Console.WriteLine($"Index {index}: {numbers[index]}");
index++;
}
Console.WriteLine("\nUsing do-while loop:");
index = 0;
do
{
Console.WriteLine($"Index {index}: {numbers[index]}");
index++;
} while (index < numbers.Length);
Console.WriteLine("\nUsing ArraySegment for partial iteration:");
ArraySegment<int> segment = new ArraySegment<int>(numbers, 1, 3);
foreach (int value in segment)
{
Console.WriteLine("Segment value: " + value);
}
Console.WriteLine("\nUsing custom iterator:");
foreach (int value in GetEvenNumbers(numbers))
{
Console.WriteLine("Even number: " + value);
}
Console.WriteLine("\nUsing Span<T> for efficient access:");
Span<int> span = numbers.AsSpan(1, 3);
foreach (int value in span)
{
Console.WriteLine("Slice value: " + value);
}
}
static IEnumerable<int> GetEvenNumbers(int[] array)
{
foreach (int number in array)
{
if (number % 2 == 0)
{
yield return number;
}
}
}
}
}
Using Array.ForEach: Number: 10 Number: 20 Number: 30 Number: 40 Number: 50 Using LINQ (convert to list first): Number: 10 Number: 20 Number: 30 Number: 40 Number: 50 Using while loop: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50 Using do-while loop: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50 Using ArraySegment for partial iteration: Segment value: 20 Segment value: 30 Segment value: 40 Using custom iterator: Even number: 10 Even number: 20 Even number: 30 Even number: 40 Even number: 50 Using Span<T> for efficient access: Slice value: 20 Slice value: 30 Slice value: 40