Arrays
Store many values of the same type in one variable, access them by index, loop through them, and use the Array helpers.
Creating arrays
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
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
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
| Code | Does |
|---|---|
Array.Sort(a) | |
Array.Reverse(a) | |
Array.IndexOf(a, x) | x, or -1 |
a.Contains(x) | true if found (needs using System.Linq;, included by default) |
a.Max(), a.Min(), a.Sum(), a.Average() | |
string.Join(", ", a) |
Arrays are reference types
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
Practice
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
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 throwsIndexOutOfRangeException.Loop with foreachto read,forwhen you need the index.Assigning an array copies the reference, not the elements.