<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. C#
  3. Arrays and methods
All lessons in this course

Lesson 11 of 60 13 minBeginner

Arrays

Store many values of the same type in one variable, access them by index, loop through them, and use the Array helpers.

Imagine storing the marks of 60 students in 60 separate variables. An array solves this: one variable holding a fixed-size, ordered row of values of the same type. Each value is an element, reached by its index, starting at 0.

Interactive

An array is a row of numbered slots

Read or change a slot by its index, try an index that doesn't exist, or loop through all of them.

int[] scores = new int[] { 45, 80, 62, 90, 73 };

scores.Length = 5 · first index 0 · last index 4

scores[0]is 45: the first element is at index 0, not 1.

Creating arrays

Program.cs
int[] scores = new int[5];                 // 5 slots, all 0string[] names = new string[3];            // 3 slots, all nullint[] marks = { 45, 80, 62, 90, 73 };      // create and filldouble[] prices = new double[] { 9.5, 12.0 }; Console.WriteLine(marks.Length);   // 5Console.WriteLine(marks[0]);       // first: 45Console.WriteLine(marks[^1]);      // last (index from end): 73
Output
5
45
73

Reading and writing elements

Program.cs
int[] marks = { 45, 80, 62, 90, 73 };marks[2] = 65;             // change the third elementint first = marks[0];// marks[5] = 10;          // IndexOutOfRangeException: last index is 4Console.WriteLine(string.Join(", ", marks));
Output
45, 80, 65, 90, 73

Looping through an array

Stats.cs
int[] marks = { 45, 80, 62, 90, 73 }; int total = 0;int highest = marks[0];foreach (int m in marks){    total += m;    if (m > highest) highest = m;}double average = (double)total / marks.Length; Console.WriteLine($"Total {total}, average {average:F1}, highest {highest}"); // Use for when you need the index:for (int i = 0; i < marks.Length; i++)    Console.WriteLine($"Student {i + 1}: {marks[i]}");
Output
Total 350, average 70.0, highest 90
Student 1: 45
Student 2: 80
...

Useful Array helpers

CodeDoes
Array.Sort(a)sorts the array in place (smallest first)
Array.Reverse(a)reverses the order in place
Array.IndexOf(a, x)index of x, or -1
a.Contains(x)true if found (needs using System.Linq;, included by default)
a.Max(), a.Min(), a.Sum(), a.Average()quick statistics (LINQ)
string.Join(", ", a)turn the array into one string

Arrays are reference types

Program.cs
int[] a = { 1, 2, 3 };int[] b = a;        // b points to the SAME array, not a copyb[0] = 99;Console.WriteLine(a[0]);   // 99! int[] c = (int[])a.Clone();  // a real copyc[1] = 0;Console.WriteLine(a[1]);   // still 2
Output
99
2
Quick check

For int[] a = new int[4];, what is the last valid index?

Quick check

What is in new bool[3] right after creation?

Practice

Given int[] nums = { 4, 9, 2, 7, 9, 1 };, count how many numbers are even and print the largest value and its index.

Show the solution
Solution.cs
int[] nums = { 4, 9, 2, 7, 9, 1 };int evens = 0, maxIndex = 0; for (int i = 0; i < nums.Length; i++){    if (nums[i] % 2 == 0) evens++;    if (nums[i] > nums[maxIndex]) maxIndex = i;}Console.WriteLine($"Even numbers: {evens}");Console.WriteLine($"Largest: {nums[maxIndex]} at index {maxIndex}");
Output
Even numbers: 2
Largest: 9 at index 1

Remember

  • An array holds a fixed number of same-type values: int[] a = { 1, 2, 3 };.
  • Indexes run from 0 to Length - 1; outside that throws IndexOutOfRangeException.
  • Loop with foreach to read, for when you need the index.
  • Assigning an array copies the reference, not the elements.
0 of 60 lessons completed