C# Arrays
Arrays are fundamental data structures in any programming language, including C#. They allow you to store multiple values of the same type in a single variable, making it easier to manage and manipulate collections of data.
What is an Array?
An array is a collection of elements of the same type, stored in contiguous memory locations. Each element in an array is accessed using an index, which starts from 0 (the first element) and goes up to the length of the array minus one.
Think of an array like a row of mailboxes - each box can hold an item, and you access a specific box using its position number.
Declaring and Initializing Arrays in C#
Basic Array Declaration
In C#, you can declare an array using the following syntax:
// Type[] arrayName;
int[] numbers;
string[] names;
Array Initialization
You can initialize an array in several ways:
Method 1: Initialize with a specific size
int[] numbers = new int[5]; // Creates an array of 5 integers (all initialized to 0)
Method 2: Initialize with values
int[] numbers = new int[] { 10, 20, 30, 40, 50 };
// Shorthand syntax
int[] numbers = { 10, 20, 30, 40, 50 };
Method 3: Declare first, initialize later
string[] fruits;
fruits = new string[] { "Apple", "Orange", "Banana", "Mango" };
Accessing Array Elements
You access array elements using their index position within square brackets:
int[] scores = { 85, 92, 78, 95, 88 };
Console.WriteLine(scores[0]); // Output: 85 (first element)
Console.WriteLine(scores[2]); // Output: 78 (third element)
// Modifying an element
scores[1] = 94;
Console.WriteLine(scores[1]); // Output: 94
Array Properties and Methods
Finding the Length of an Array
The Length
property returns the total number of elements in the array:
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine($"The array has {numbers.Length} elements"); // Output: The array has 5 elements
Common Array Methods
Here are some useful methods for working with arrays:
Array.Sort()
int[] numbers = { 5, 3, 8, 1, 9, 2 };
Array.Sort(numbers);
// numbers is now { 1, 2, 3, 5, 8, 9 }
foreach (int num in numbers)
{
Console.Write($"{num} "); // Output: 1 2 3 5 8 9
}
Array.Reverse()
int[] numbers = { 1, 2, 3, 4, 5 };
Array.Reverse(numbers);
// numbers is now { 5, 4, 3, 2, 1 }
Array.IndexOf()
string[] fruits = { "Apple", "Orange", "Banana", "Mango" };
int position = Array.IndexOf(fruits, "Banana");
Console.WriteLine($"Banana is at index {position}"); // Output: Banana is at index 2
Iterating Through Arrays
Using for Loop
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Element {i}: {numbers[i]}");
}
// Output:
// Element 0: 10
// Element 1: 20
// Element 2: 30
// Element 3: 40
// Element 4: 50
Using foreach Loop
The foreach
loop provides a cleaner way to iterate through all elements:
string[] colors = { "Red", "Green", "Blue", "Yellow" };
foreach (string color in colors)
{
Console.WriteLine(color);
}
// Output:
// Red
// Green
// Blue
// Yellow
Multidimensional Arrays
C# supports both rectangular and jagged multidimensional arrays.
Rectangular Arrays (2D)
A rectangular array has a fixed number of rows and columns:
// Declaration and initialization
int[,] matrix = new int[3, 4]; // 3 rows, 4 columns
// Initialize with values
int[,] matrix = new int[,]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
// Accessing elements
Console.WriteLine(matrix[1, 2]); // Output: 7 (row 1, column 2)
// Finding dimensions
int rows = matrix.GetLength(0); // 3
int columns = matrix.GetLength(1); // 4
// Iterating through 2D array
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write($"{matrix[i, j]} ");
}
Console.WriteLine();
}
// Output:
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
Jagged Arrays (Arrays of Arrays)
A jagged array is an array of arrays, where each inner array can have a different length:
// Declaration
int[][] jaggedArray = new int[3][];
// Initialize inner arrays
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
// Accessing elements
Console.WriteLine(jaggedArray[2][1]); // Output: 7
// Iterating through jagged array
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write($"{jaggedArray[i][j]} ");
}
Console.WriteLine();
}
// Output:
// 1 2 3
// 4 5
// 6 7 8 9
Practical Examples
Example 1: Calculate Average Score
int[] scores = { 85, 92, 78, 95, 88 };
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
double average = (double)sum / scores.Length;
Console.WriteLine($"The average score is: {average:F2}");
// Output: The average score is: 87.60
Example 2: Find the Maximum Value
int[] numbers = { 23, 45, 12, 67, 89, 34 };
int max = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
if (numbers[i] > max)
{
max = numbers[i];
}
}
Console.WriteLine($"The maximum value is: {max}");
// Output: The maximum value is: 89
// Alternative: Using built-in method
int maxValue = numbers.Max();
Console.WriteLine($"The maximum value is: {maxValue}");
// Output: The maximum value is: 89
Example 3: Filtering an Array
int[] values = { 10, 25, 33, 42, 57, 68, 71, 84, 95 };
int[] evenNumbers = values.Where(n => n % 2 == 0).ToArray();
Console.WriteLine("Even numbers:");
foreach (int num in evenNumbers)
{
Console.Write($"{num} ");
}
// Output: Even numbers: 10 42 68 84
Example 4: Temperature Tracking System
// A real-world example: Tracking daily temperatures for a week
double[] weeklyTemperatures = { 72.5, 75.3, 78.2, 77.0, 76.8, 79.5, 81.2 };
string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
// Find the average temperature
double sum = 0;
foreach (double temp in weeklyTemperatures)
{
sum += temp;
}
double averageTemp = sum / weeklyTemperatures.Length;
// Find the hottest day
double maxTemp = weeklyTemperatures.Max();
int hottestDayIndex = Array.IndexOf(weeklyTemperatures, maxTemp);
string hottestDay = daysOfWeek[hottestDayIndex];
// Find the coldest day
double minTemp = weeklyTemperatures.Min();
int coldestDayIndex = Array.IndexOf(weeklyTemperatures, minTemp);
string coldestDay = daysOfWeek[coldestDayIndex];
Console.WriteLine($"Weekly Weather Report:");
Console.WriteLine($"Average temperature: {averageTemp:F1}°F");
Console.WriteLine($"Hottest day: {hottestDay} ({maxTemp}°F)");
Console.WriteLine($"Coldest day: {coldestDay} ({minTemp}°F)");
// Output:
// Weekly Weather Report:
// Average temperature: 77.2°F
// Hottest day: Sunday (81.2°F)
// Coldest day: Monday (72.5°F)
Common Pitfalls and Best Practices
Avoiding Index Out of Range Exceptions
One of the most common errors when working with arrays is trying to access an element that doesn't exist:
int[] numbers = { 1, 2, 3 };
// The following line will throw an IndexOutOfRangeException
// Console.WriteLine(numbers[3]); // There is no element at index 3!
// Better approach: check bounds first
int index = 3;
if (index < numbers.Length)
{
Console.WriteLine(numbers[index]);
}
else
{
Console.WriteLine("Index is out of range.");
}
Passing Arrays to Methods
Arrays are reference types, so when you pass an array to a method, changes to the array elements will affect the original array:
void Main()
{
int[] values = { 1, 2, 3, 4, 5 };
Console.WriteLine("Before: " + string.Join(", ", values));
DoubleValues(values);
Console.WriteLine("After: " + string.Join(", ", values));
}
void DoubleValues(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] *= 2;
}
}
// Output:
// Before: 1, 2, 3, 4, 5
// After: 2, 4, 6, 8, 10
Summary
Arrays in C# provide a powerful way to work with collections of data of the same type. Key points to remember:
- Arrays store multiple elements of the same data type
- Array indices start at 0
- Arrays have a fixed size once created
- C# provides many built-in methods to work with arrays
- Arrays can be single-dimensional, multi-dimensional, or jagged
- Arrays are reference types, so they're passed by reference to methods
Arrays form the foundation for understanding more advanced data structures in C#. Mastering arrays will help you better understand collections, lists, and other data structures in the language.
Practice Exercises
-
Create an array of 10 integers, fill it with random numbers between 1 and 100, and calculate the sum of all even numbers in the array.
-
Write a program that takes an array of strings and returns a new array containing only the strings that start with a vowel.
-
Create a 3x3 matrix (2D array) representing a tic-tac-toe board. Write methods to place 'X' or 'O' on the board and check if someone has won.
-
Implement a method that takes two sorted arrays and merges them into a single sorted array.
-
Write a program that simulates rolling a dice 1000 times and uses an array to count how many times each number (1-6) appears.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)