Arrays are one of the fundamental data structures in C#, allowing storage of multiple elements of the same type in a contiguous memory block. Looping over arrays is essential to access or manipulate each element efficiently. C# provides various looping constructs to iterate through arrays, each with unique advantages and typical use cases.
An array in C# is a fixed-size, zero-based indexed collection of elements of the same type. Once declared, the size of an array cannot change. Accessing each element individually requires iterating or "looping" over it.
Looping constructs help automate repetitive access and modification of array elements. Understanding different loop types and their applicability improves code clarity, efficiency, and maintainability.
Before diving into looping, let's review some basics about arrays.
// Declare an integer array with 5 elements
int[] numbers = new int[5];
// Initialize with values
int[] primes = { 2, 3, 5, 7, 11 };
// Declare and initialize with new keyword
string[] fruits = new string[] { "apple", "banana", "cherry" };
Array elements are accessed via zero-based indices:
int firstPrime = primes[0]; // 2
string firstFruit = fruits[0]; // "apple"
int length = primes.Length; // 5
The for loop is the most common loop used to iterate arrays because it provides direct control over the index.
for (int i = 0; i < array.Length; i++)
{
// Access element at index i
var element = array[i];
// Process element
}
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Element at index {i} is {numbers[i]}");
}
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] *= 2; // Double each element
}
for (int i = numbers.Length - 1; i >= 0; i--)
{
Console.WriteLine(numbers[i]);
}
for (int i = 0; i < numbers.Length; i += 2)
{
Console.WriteLine(numbers[i]);
}
The foreach loop is specifically designed for iterating over collections like arrays, lists, and other enumerable types.
foreach (var element in array)
{
// Use element directly
}
string[] fruits = { "apple", "banana", "cherry" };
foreach (var fruit in fruits)
{
Console.WriteLine(fruit);
}
int index = 0;
foreach (var fruit in fruits)
{
Console.WriteLine($"Element {index}: {fruit}");
index++;
}
While loops are less commonly used for array iteration but can be useful in certain scenarios.
int i = 0;
while (i < array.Length)
{
var element = array[i];
i++;
}
int[] numbers = { 10, 20, 30 };
int i = 0;
while (i < numbers.Length)
{
Console.WriteLine(numbers[i]);
i++;
}
int i = 0;
do
{
var element = array[i];
i++;
} while (i < array.Length);
C# supports multidimensional arrays (rectangular arrays) and jagged arrays (arrays of arrays). Looping over these requires nested loops.
int[,] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
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();
}
int[][] jagged = new int[][]
{
new int[] {1, 2, 3},
new int[] {4, 5},
new int[] {6, 7, 8, 9}
};
for (int i = 0; i < jagged.Length; i++)
{
for (int j = 0; j < jagged[i].Length; j++)
{
Console.Write(jagged[i][j] + " ");
}
Console.WriteLine();
}
int[] numbers = { 10, 20, 30, 40 };
int target = 30;
int index = -1;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target)
{
index = i;
break; // Stop after finding first occurrence
}
}
Console.WriteLine(index); // Output: 2
int[] numbers = { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (var num in numbers)
{
sum += num;
}
Console.WriteLine($"Sum: {sum}"); // 15
int[] numbers = { 1, 2, 3, 4, 5, 6 };
List evens = new List();
foreach (var num in numbers)
{
if (num % 2 == 0)
{
evens.Add(num);
}
}
Console.WriteLine(string.Join(", ", evens)); // 2, 4, 6
int[] numbers = { 1, 2, 3 };
int[] doubled = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
doubled[i] = numbers[i] * 2;
}
Console.WriteLine(string.Join(", ", doubled)); // 2, 4, 6int[] array = { 1, 2, 3, 4, 5 };
int len = array.Length;
for (int i = 0; i < len; i++)
{
Console.WriteLine(array[i]);
}
While LINQ is more declarative, it internally loops over arrays.
int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}
For CPU-intensive operations on large arrays, parallel loops can improve performance by utilizing multiple threads.
int[] numbers = new int[1000];
// Initialize array
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i;
}
// Parallel processing
System.Threading.Tasks.Parallel.For(0, numbers.Length, i =>
{
numbers[i] = numbers[i] * numbers[i]; // square each element
});
C# 7.2+ introduced Span<T>, a memory-safe and efficient way to create slices (sub-arrays) without copying data. You can loop over spans like arrays.
int[] numbers = { 1, 2, 3, 4, 5 };
Span<int> slice = numbers.AsSpan(1, 3); // Slice from index 1, length 3
foreach (var n in slice)
{
Console.WriteLine(n); // Outputs 2, 3, 4
}
int[] scores = { 85, 92, 78, 90, 100 };
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine($"User {i + 1}: Score = {scores[i]}");
}
int[] values = { 5, 12, 9, 21, 7 };
int max = values[0];
foreach (var val in values)
{
if (val > max)
max = val;
}
Console.WriteLine($"Maximum value: {max}");
string[] words = { "apple", "banana", "apple", "orange", "banana", "apple" };
Dictionary<string, int> counts = new Dictionary<string, int>();
foreach (var word in words)
{
if (counts.ContainsKey(word))
counts[word]++;
else
counts[word] = 1;
}
foreach (var pair in counts)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
Looping over arrays in C# is a foundational skill for any developer. Understanding the available looping constructs and their best use cases helps you write efficient, clear, and maintainable code.
Key points covered:
Mastering these techniques allows you to work confidently with arrays in any C# application, from simple scripts to complex, high-performance systems.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved