Array Basics
Arrays allow you to store multiple values of the same type in a single variable. This lesson covers array declaration, initialization, and basic operations.
What is an Array?
An array is a fixed-size collection of elements of the same type:
csharp1// Instead of separate variables2int score1 = 85;3int score2 = 90;4int score3 = 78;56// Use an array7int[] scores = { 85, 90, 78 };
Declaring Arrays
Method 1: Initialize with Values
csharp1int[] numbers = { 1, 2, 3, 4, 5 };2string[] names = { "Alice", "Bob", "Charlie" };3double[] prices = { 19.99, 29.99, 9.99 };4bool[] flags = { true, false, true };
Method 2: Declare with Size
csharp1int[] scores = new int[5]; // 5 elements, all initialized to 02string[] names = new string[3]; // 3 elements, all null3double[] values = new double[10]; // 10 elements, all 0.0
Method 3: Declare and Initialize
csharp1int[] numbers = new int[] { 10, 20, 30 };2// Or shorter3int[] numbers = new[] { 10, 20, 30 };
Array Indexing
Arrays are zero-indexed (first element is at index 0):
csharp1string[] fruits = { "Apple", "Banana", "Cherry", "Date" };2// Index 0 Index 1 Index 2 Index 334Console.WriteLine(fruits[0]); // Apple5Console.WriteLine(fruits[1]); // Banana6Console.WriteLine(fruits[2]); // Cherry7Console.WriteLine(fruits[3]); // Date
Modifying Elements
csharp1int[] numbers = { 10, 20, 30 };23numbers[0] = 100; // Change first element4numbers[2] = 300; // Change third element56// numbers is now { 100, 20, 300 }
Index from End (C# 8+)
csharp1string[] colors = { "Red", "Green", "Blue", "Yellow" };23Console.WriteLine(colors[^1]); // Yellow (last element)4Console.WriteLine(colors[^2]); // Blue (second to last)
Array Length
The Length property tells you how many elements are in the array:
csharp1int[] numbers = { 5, 10, 15, 20, 25 };23Console.WriteLine(numbers.Length); // 545// Last valid index is Length - 16int lastIndex = numbers.Length - 1;7Console.WriteLine(numbers[lastIndex]); // 25
Iterating Over Arrays
Using for Loop
csharp1int[] scores = { 85, 92, 78, 95, 88 };23for (int i = 0; i < scores.Length; i++)4{5 Console.WriteLine($"Score {i + 1}: {scores[i]}");6}
Using foreach Loop
csharp1string[] names = { "Alice", "Bob", "Charlie" };23foreach (string name in names)4{5 Console.WriteLine($"Hello, {name}!");6}
When to Use Which
csharp1// Use for when you need the index2for (int i = 0; i < items.Length; i++)3{4 Console.WriteLine($"Item {i}: {items[i]}");5}67// Use foreach when you just need the values8foreach (var item in items)9{10 Console.WriteLine(item);11}1213// Use for when you need to modify elements14for (int i = 0; i < numbers.Length; i++)15{16 numbers[i] *= 2; // Double each element17}
Default Values
Uninitialized array elements have default values:
| Type | Default Value |
|---|---|
| int, double, etc. | 0 |
| bool | false |
| char | '\0' |
| string, objects | null |
csharp1int[] nums = new int[3];2// nums = { 0, 0, 0 }34bool[] flags = new bool[3];5// flags = { false, false, false }67string[] texts = new string[3];8// texts = { null, null, null }
Common Operations
Finding Sum and Average
csharp1int[] scores = { 85, 92, 78, 95, 88 };23int sum = 0;4foreach (int score in scores)5{6 sum += score;7}89double average = (double)sum / scores.Length;10Console.WriteLine($"Sum: {sum}"); // 43811Console.WriteLine($"Average: {average:F1}"); // 87.6
Finding Min and Max
csharp1int[] numbers = { 45, 12, 78, 34, 56 };23int min = numbers[0];4int max = numbers[0];56foreach (int num in numbers)7{8 if (num < min) min = num;9 if (num > max) max = num;10}1112Console.WriteLine($"Min: {min}"); // 1213Console.WriteLine($"Max: {max}"); // 78
Searching for an Element
csharp1string[] names = { "Alice", "Bob", "Charlie" };2string searchFor = "Bob";3bool found = false;4int foundIndex = -1;56for (int i = 0; i < names.Length; i++)7{8 if (names[i] == searchFor)9 {10 found = true;11 foundIndex = i;12 break;13 }14}1516if (found)17{18 Console.WriteLine($"Found '{searchFor}' at index {foundIndex}");19}
Array Bounds
Accessing an invalid index throws an exception:
csharp1int[] numbers = { 1, 2, 3 };23// Valid indexes: 0, 1, 24Console.WriteLine(numbers[0]); // OK5Console.WriteLine(numbers[2]); // OK67// Invalid - throws IndexOutOfRangeException8// Console.WriteLine(numbers[3]);9// Console.WriteLine(numbers[-1]);
Safe Access Pattern
csharp1int[] numbers = { 1, 2, 3, 4, 5 };2int index = 10;34if (index >= 0 && index < numbers.Length)5{6 Console.WriteLine(numbers[index]);7}8else9{10 Console.WriteLine("Index out of bounds!");11}
Practical Example
csharp1Console.WriteLine("=== Temperature Tracker ===");23double[] temperatures = new double[7];4string[] days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };56// Input temperatures7for (int i = 0; i < 7; i++)8{9 Console.Write($"Enter temperature for {days[i]}: ");10 double.TryParse(Console.ReadLine(), out temperatures[i]);11}1213// Calculate statistics14double sum = 0;15double min = temperatures[0];16double max = temperatures[0];1718foreach (double temp in temperatures)19{20 sum += temp;21 if (temp < min) min = temp;22 if (temp > max) max = temp;23}2425double average = sum / temperatures.Length;2627// Display results28Console.WriteLine("\n=== Weekly Summary ===");29for (int i = 0; i < 7; i++)30{31 Console.WriteLine($"{days[i]}: {temperatures[i]:F1}°");32}33Console.WriteLine($"\nAverage: {average:F1}°");34Console.WriteLine($"Min: {min:F1}°");35Console.WriteLine($"Max: {max:F1}°");
Summary
In this lesson, you learned:
- Arrays store multiple values of the same type
- Arrays are zero-indexed (first element is at index 0)
- Use
Lengthto get the number of elements - Iterate with
for(when you need index) orforeach(simpler) - Default values depend on the element type
- Always check bounds to avoid IndexOutOfRangeException
Next, we'll explore built-in array operations.