Arrays
Store many values of the same type in one variable and process them with loops.
11 min read
You will learn
- Create and initialize arrays
- Read and write elements by index
- Loop over arrays to compute results
- Understand that arrays have a fixed size
Many values, one variable
Storing five test scores in five variables (score1, score2…) doesn't scale. An array holds a fixed number of values of the same type, each identified by a position — its index.
int[] scores = { 90, 72, 85, 64, 99 };
// [0] [1] [2] [3] [4]
Console.WriteLine(scores[0]); // 90 — the first element
Console.WriteLine(scores[^1]); // 99 — the last element
Console.WriteLine(scores.Length); // 5
scores[1] = 75; // replace an elementIndexes start at 0, so the last valid index is Length - 1.
Creating arrays
int[] a = { 1, 2, 3 }; // values known up front
int[] b = new int[5]; // 5 elements, all 0
string[] names = new string[3]; // 3 elements, all null
var c = new[] { 1.5, 2.5 }; // type inferred: double[]
int[] d = [1, 2, 3]; // C# 12 collection expressionNew arrays are filled with default values: 0 for numbers, false for bool, null for strings and other reference types.
Fixed size
An array's length is set when it's created and can never change. There's no Add method. For a collection that grows, use List<T> — coming in the Collections module.
Out of bounds
int[] values = { 10, 20, 30 };
Console.WriteLine(values[3]); // 💥 IndexOutOfRangeException.NET always checks array bounds — you get a clear exception instead of silently reading garbage memory, as happens in C.
Looping over arrays
Use foreach when you only need the values:
int total = 0;
foreach (int score in scores)
{
total += score;
}
double average = (double)total / scores.Length;Use for when you need the index — to modify elements, compare neighbours, or walk backwards:
for (int i = 0; i < scores.Length; i++)
{
scores[i] += 5; // bonus points for everyone
}
for (int i = scores.Length - 1; i >= 0; i--)
{
Console.Write($"{scores[i]} "); // print in reverse
}Finding things
The "best so far" pattern finds a maximum, minimum, or first match:
int highest = scores[0]; // start with a real element, not 0!
foreach (int s in scores)
{
if (s > highest) highest = s;
}Starting with 0 would be wrong for arrays of negative numbers — a classic bug.
Helpful built-ins
Array.Sort(scores); // sorts in place
Array.Reverse(scores); // reverses in place
int index = Array.IndexOf(scores, 85); // -1 if not found
bool has = scores.Contains(85); // from System.Linq
Console.WriteLine(string.Join(", ", scores)); // print all elementsLater, LINQ (Track 4) will give you one-liners like scores.Max() and scores.Average() — but writing these loops yourself first is the best way to understand what those methods do.
Multi-dimensional arrays
A grid uses two indexes:
int[,] board = new int[3, 3];
board[1, 1] = 5; // the centre cell
Console.WriteLine(board.GetLength(0)); // 3 rowsTry it
C# runtime not loaded
Key takeaways
- Arrays hold a fixed number of same-typed values, indexed from
0toLength - 1. - New arrays contain default values; accessing outside the bounds throws.
foreachto read every value,forwhen you need the index.- Arrays can't grow — use
List<T>for that.
Exercise
Implement Max (the largest number — arrays may contain only negative numbers), Average (as a double), Reversed (a NEW array in reverse order — don't change the input) and CountGreaterThan (how many items are strictly greater than limit). Use loops rather than LINQ.
C# runtime not loaded
Hint 1
Max: start with numbers[0] (not 0!) as the best so far, then compare every element.
Hint 2
Average: sum into an int, then divide as a double: (double)sum / numbers.Length.
Hint 3
Reversed: create var result = new int[numbers.Length]; and copy numbers[i] into result[numbers.Length - 1 - i].
Show solution
int Max(int[] numbers)
{
int max = numbers[0];
foreach (int n in numbers)
{
if (n > max) max = n;
}
return max;
}
double Average(int[] numbers)
{
int sum = 0;
foreach (int n in numbers) sum += n;
return (double)sum / numbers.Length;
}
int[] Reversed(int[] numbers)
{
var result = new int[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
result[numbers.Length - 1 - i] = numbers[i];
}
return result;
}
int CountGreaterThan(int[] numbers, int limit)
{
int count = 0;
foreach (int n in numbers)
{
if (n > limit) count++;
}
return count;
}
int[] data = { 3, 9, 2 };
Console.WriteLine(Max(data));
Console.WriteLine(Average(data));
Console.WriteLine(string.Join(", ", Reversed(data)));Quiz
4 questions · 3 correct to pass1.Given `int[] a = new int[3];`, what is `a[1]`?
2.Given `int[] a = { 10, 20, 30 };`, what happens with `a[3]`?
3.How do you add a fourth element to an existing array of length 3?
4.After `int[] a = { 1, 2 }; int[] b = a; b[0] = 99;` what is `a[0]`?
To complete this lesson
- ○ Solve the exercise
- ○ Pass the quiz (3/4 correct)