C# Arrays
Store multiple values in a single variable
📦 What are Arrays?
Arrays store multiple values of the same type in a single variable. Instead of creating separate variables, you can store many values together and access them using an index number.
// Create an array of numbers
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[0]); // Output: 10
Array Fundamentals
Declaration
Define array type and size
int[] numbers;
string[] names;
Initialization
Assign values to array
int[] nums = {1, 2, 3};
// or
int[] nums = new int[3];
Indexing
Access elements by position
int first = nums[0];
int second = nums[1];
Length Property
Get number of elements
int size = nums.Length;
Console.WriteLine(size);
🔹 Creating Arrays
Arrays in C# are fixed-size, strongly-typed collections of elements, all of the same type, stored in contiguous memory locations. You can create arrays by specifying the type and size (e.g., int[] numbers = new int[5];) or initialize them with values directly (e.g., int[] numbers = {1, 2, 3};). Multidimensional arrays (rectangular or jagged) are also supported for complex data structures. Arrays offer fast, index-based access (O(1) time complexity) and are the foundation for many higher-level collections. For dynamic resizing, consider using List<T> from System.Collections.Generic, which internally uses an array.
// Method 1: Declare and initialize with values
int[] numbers = { 1, 2, 3, 4, 5 };
// Method 2: Declare with size, then assign values
int[] scores = new int[3];
scores[0] = 85;
scores[1] = 90;
scores[2] = 78;
// Method 3: Declare and initialize with new keyword
string[] fruits = new string[] { "Apple", "Banana", "Orange" };
// Display array elements
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(scores[1]); // Output: 90
Console.WriteLine(fruits[2]); // Output: Orange
Output:
1 90 Orange
🔹 Accessing Array Elements
Array elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and so on.
string[] colors = { "Red", "Green", "Blue", "Yellow" };
// Access individual elements
Console.WriteLine("First color: " + colors[0]);
Console.WriteLine("Second color: " + colors[1]);
Console.WriteLine("Last color: " + colors[3]);
// Modify an element
colors[2] = "Purple";
Console.WriteLine("Modified third color: " + colors[2]);
// Output:
// First color: Red
// Second color: Green
// Last color: Yellow
// Modified third color: Purple
Output:
First color: Red Second color: Green Last color: Yellow Modified third color: Purple
🔹 Array Length Property
The Length property returns the total number of elements in an array. This is useful for loops and validation.
int[] numbers = { 10, 20, 30, 40, 50 };
// Get array length
int arraySize = numbers.Length;
Console.WriteLine("Array has " + arraySize + " elements");
// Use length in a loop
Console.WriteLine("\nAll elements:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Element " + i + ": " + numbers[i]);
}
// Output:
// Array has 5 elements
//
// All elements:
// Element 0: 10
// Element 1: 20
// Element 2: 30
// Element 3: 40
// Element 4: 50
Output:
Array has 5 elements All elements: Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50
🔹 Looping Through Arrays
For loops are commonly used to iterate over array elements by index. By using the array's Length property as the loop condition, you can automatically process every item regardless of the array's size. This method is efficient for tasks like calculating sums, finding values, or displaying all elements in a collection sequentially.
string[] animals = { "Dog", "Cat", "Bird", "Fish" };
// Using for loop
Console.WriteLine("Using for loop:");
for (int i = 0; i < animals.Length; i++)
{
Console.WriteLine(animals[i]);
}
// Using foreach loop
Console.WriteLine("\nUsing foreach loop:");
foreach (string animal in animals)
{
Console.WriteLine(animal);
}
// Output:
// Using for loop:
// Dog
// Cat
// Bird
// Fish
//
// Using foreach loop:
// Dog
// Cat
// Bird
// Fish
Output:
Using for loop: Dog Cat Bird Fish Using foreach loop: Dog Cat Bird Fish
🔹 Multi-Dimensional Arrays
C# supports multi-dimensional arrays, which are arrays with more than one dimension. The most common is a 2D array (like a table or grid).
// 2D array (3 rows, 2 columns)
int[,] matrix = {
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
// Access elements
Console.WriteLine("Element at [0,0]: " + matrix[0, 0]); // 1
Console.WriteLine("Element at [1,1]: " + matrix[1, 1]); // 4
Console.WriteLine("Element at [2,0]: " + matrix[2, 0]); // 5
// Loop through 2D array
Console.WriteLine("\nAll elements:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
// Output:
// Element at [0,0]: 1
// Element at [1,1]: 4
// Element at [2,0]: 5
//
// All elements:
// 1 2
// 3 4
// 5 6
Output:
Element at [0,0]: 1 Element at [1,1]: 4 Element at [2,0]: 5 All elements: 1 2 3 4 5 6
🔹 Common Array Methods
C# provides useful methods for working with arrays through the Array class:
Useful Array Methods:
- Array.Sort(): Sorts array elements in ascending order
- Array.Reverse(): Reverses the order of elements
- Array.IndexOf(): Finds the index of a specific element
- Array.Clear(): Sets elements to default values
int[] numbers = { 5, 2, 8, 1, 9 };
// Sort array
Array.Sort(numbers);
Console.WriteLine("Sorted: " + string.Join(", ", numbers));
// Reverse array
Array.Reverse(numbers);
Console.WriteLine("Reversed: " + string.Join(", ", numbers));
// Find index of element
int index = Array.IndexOf(numbers, 5);
Console.WriteLine("Index of 5: " + index);
// Output:
// Sorted: 1, 2, 5, 8, 9
// Reversed: 9, 8, 5, 2, 1
// Index of 5: 2
Output:
Sorted: 1, 2, 5, 8, 9 Reversed: 9, 8, 5, 2, 1 Index of 5: 2
🔹 Practical Example: Grade Calculator
A grade calculator method demonstrates effective parameter usage by computing letter grades from scores. For example, string CalculateGrade(double score, bool isExtraCredit = false) adjusts the score if extra credit applies, then returns "A", "B", etc. This method uses optional parameters for flexibility and returns a meaningful result. It shows how parameters enable customization (like extra credit) while keeping the interface simple. Such practical examples highlight how well-designed parameters create intuitive, reusable business logic.
// Student grades
int[] grades = { 85, 92, 78, 90, 88 };
// Calculate sum
int sum = 0;
foreach (int grade in grades)
{
sum += grade;
}
// Calculate average
double average = (double)sum / grades.Length;
// Display results
Console.WriteLine("Grades: " + string.Join(", ", grades));
Console.WriteLine("Total: " + sum);
Console.WriteLine("Average: " + average);
// Output:
// Grades: 85, 92, 78, 90, 88
// Total: 433
// Average: 86.6
Output:
Grades: 85, 92, 78, 90, 88 Total: 433 Average: 86.6