12 minlesson

Array Basics

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:

csharp
1// Instead of separate variables
2int score1 = 85;
3int score2 = 90;
4int score3 = 78;
5
6// Use an array
7int[] scores = { 85, 90, 78 };

Declaring Arrays

Method 1: Initialize with Values

csharp
1int[] 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

csharp
1int[] scores = new int[5]; // 5 elements, all initialized to 0
2string[] names = new string[3]; // 3 elements, all null
3double[] values = new double[10]; // 10 elements, all 0.0

Method 3: Declare and Initialize

csharp
1int[] numbers = new int[] { 10, 20, 30 };
2// Or shorter
3int[] numbers = new[] { 10, 20, 30 };

Array Indexing

Arrays are zero-indexed (first element is at index 0):

csharp
1string[] fruits = { "Apple", "Banana", "Cherry", "Date" };
2// Index 0 Index 1 Index 2 Index 3
3
4Console.WriteLine(fruits[0]); // Apple
5Console.WriteLine(fruits[1]); // Banana
6Console.WriteLine(fruits[2]); // Cherry
7Console.WriteLine(fruits[3]); // Date

Modifying Elements

csharp
1int[] numbers = { 10, 20, 30 };
2
3numbers[0] = 100; // Change first element
4numbers[2] = 300; // Change third element
5
6// numbers is now { 100, 20, 300 }

Index from End (C# 8+)

csharp
1string[] colors = { "Red", "Green", "Blue", "Yellow" };
2
3Console.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:

csharp
1int[] numbers = { 5, 10, 15, 20, 25 };
2
3Console.WriteLine(numbers.Length); // 5
4
5// Last valid index is Length - 1
6int lastIndex = numbers.Length - 1;
7Console.WriteLine(numbers[lastIndex]); // 25

Iterating Over Arrays

Using for Loop

csharp
1int[] scores = { 85, 92, 78, 95, 88 };
2
3for (int i = 0; i < scores.Length; i++)
4{
5 Console.WriteLine($"Score {i + 1}: {scores[i]}");
6}

Using foreach Loop

csharp
1string[] names = { "Alice", "Bob", "Charlie" };
2
3foreach (string name in names)
4{
5 Console.WriteLine($"Hello, {name}!");
6}

When to Use Which

csharp
1// Use for when you need the index
2for (int i = 0; i < items.Length; i++)
3{
4 Console.WriteLine($"Item {i}: {items[i]}");
5}
6
7// Use foreach when you just need the values
8foreach (var item in items)
9{
10 Console.WriteLine(item);
11}
12
13// Use for when you need to modify elements
14for (int i = 0; i < numbers.Length; i++)
15{
16 numbers[i] *= 2; // Double each element
17}

Default Values

Uninitialized array elements have default values:

TypeDefault Value
int, double, etc.0
boolfalse
char'\0'
string, objectsnull
csharp
1int[] nums = new int[3];
2// nums = { 0, 0, 0 }
3
4bool[] flags = new bool[3];
5// flags = { false, false, false }
6
7string[] texts = new string[3];
8// texts = { null, null, null }

Common Operations

Finding Sum and Average

csharp
1int[] scores = { 85, 92, 78, 95, 88 };
2
3int sum = 0;
4foreach (int score in scores)
5{
6 sum += score;
7}
8
9double average = (double)sum / scores.Length;
10Console.WriteLine($"Sum: {sum}"); // 438
11Console.WriteLine($"Average: {average:F1}"); // 87.6

Finding Min and Max

csharp
1int[] numbers = { 45, 12, 78, 34, 56 };
2
3int min = numbers[0];
4int max = numbers[0];
5
6foreach (int num in numbers)
7{
8 if (num < min) min = num;
9 if (num > max) max = num;
10}
11
12Console.WriteLine($"Min: {min}"); // 12
13Console.WriteLine($"Max: {max}"); // 78

Searching for an Element

csharp
1string[] names = { "Alice", "Bob", "Charlie" };
2string searchFor = "Bob";
3bool found = false;
4int foundIndex = -1;
5
6for (int i = 0; i < names.Length; i++)
7{
8 if (names[i] == searchFor)
9 {
10 found = true;
11 foundIndex = i;
12 break;
13 }
14}
15
16if (found)
17{
18 Console.WriteLine($"Found '{searchFor}' at index {foundIndex}");
19}

Array Bounds

Accessing an invalid index throws an exception:

csharp
1int[] numbers = { 1, 2, 3 };
2
3// Valid indexes: 0, 1, 2
4Console.WriteLine(numbers[0]); // OK
5Console.WriteLine(numbers[2]); // OK
6
7// Invalid - throws IndexOutOfRangeException
8// Console.WriteLine(numbers[3]);
9// Console.WriteLine(numbers[-1]);

Safe Access Pattern

csharp
1int[] numbers = { 1, 2, 3, 4, 5 };
2int index = 10;
3
4if (index >= 0 && index < numbers.Length)
5{
6 Console.WriteLine(numbers[index]);
7}
8else
9{
10 Console.WriteLine("Index out of bounds!");
11}

Practical Example

csharp
1Console.WriteLine("=== Temperature Tracker ===");
2
3double[] temperatures = new double[7];
4string[] days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
5
6// Input temperatures
7for (int i = 0; i < 7; i++)
8{
9 Console.Write($"Enter temperature for {days[i]}: ");
10 double.TryParse(Console.ReadLine(), out temperatures[i]);
11}
12
13// Calculate statistics
14double sum = 0;
15double min = temperatures[0];
16double max = temperatures[0];
17
18foreach (double temp in temperatures)
19{
20 sum += temp;
21 if (temp < min) min = temp;
22 if (temp > max) max = temp;
23}
24
25double average = sum / temperatures.Length;
26
27// Display results
28Console.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 Length to get the number of elements
  • Iterate with for (when you need index) or foreach (simpler)
  • Default values depend on the element type
  • Always check bounds to avoid IndexOutOfRangeException

Next, we'll explore built-in array operations.