Beginner · Arrays, strings and null · topic 10 of 43 · 30 min
Arrays: one name, many values
Explanation
Why arrays?
Storing the marks of 60 students in 60 separate variables would be painful. An array is one variable that holds many values of the same type, side by side in memory. You loop over it, sort it and pass it to methods as one thing.
Creating arrays
int[] marks = new int[5]; // 5 ints, all 0 at first
string[] days = { "Mon", "Tue", "Wed" }; // filled straight away
double[] prices = new double[] { 9.5, 20.0 };
int[] scores = [70, 85, 90]; // collection expression, C# 12+Reading and writing by index
int[] marks = { 78, 92, 65, 88 };
Console.WriteLine(marks[0]); // 78 (first)
Console.WriteLine(marks.Length); // 4
Console.WriteLine(marks[marks.Length - 1]); // 88 (last)
Console.WriteLine(marks[^1]); // 88 (^1 = first from the end)
marks[2] = 70; // change the third valueRanges: slicing an array (C# 8 and later)
int[] n = { 10, 20, 30, 40, 50 };
int[] middle = n[1..4]; // 20, 30, 40 (end is NOT included)
int[] firstTwo = n[..2]; // 10, 20
int[] lastTwo = n[^2..]; // 40, 50
Console.WriteLine(string.Join(", ", middle));Looping and printing
int[] marks = { 78, 92, 65, 88 };
int total = 0;
foreach (int m in marks) total += m;
Console.WriteLine($"Average: {(double)total / marks.Length}"); // 80.75
Console.WriteLine(marks); // System.Int32[]
Console.WriteLine(string.Join(", ", marks)); // 78, 92, 65, 88Useful Array methods
int[] marks = { 78, 92, 65, 88 };
Array.Sort(marks); // 65, 78, 88, 92 (changes the array)
Array.Reverse(marks); // 92, 88, 78, 65
int pos = Array.IndexOf(marks, 78); // 2
int missing = Array.IndexOf(marks, 100); // -1 means "not found"
Console.WriteLine($"{pos} {missing}");Arrays are reference types
An array variable does not hold the values themselves; it holds a reference, an arrow pointing to the array in memory. Copying the variable copies the arrow, not the array. Both names then point to the same lockers.
int[] a = { 1, 2, 3 };
int[] b = a; // same array, two names
b[0] = 99;
Console.WriteLine(a[0]); // 99
int[] c = (int[])a.Clone(); // a real copy
c[1] = 0;
Console.WriteLine(a[1]); // 22D arrays: grids
// 3 rows x 4 seats in a small cinema; 1 = booked
int[,] seats = new int[3, 4];
seats[0, 1] = 1;
seats[2, 3] = 1;
for (int row = 0; row < seats.GetLength(0); row++)
{
for (int col = 0; col < seats.GetLength(1); col++)
Console.Write(seats[row, col] == 1 ? "X " : "_ ");
Console.WriteLine();
}Jagged arrays: rows of different lengths
// Marks of 3 students; each took a different number of tests
int[][] tests = new int[3][];
tests[0] = new[] { 80, 75 };
tests[1] = new[] { 90, 85, 70 };
tests[2] = new[] { 60 };
Console.WriteLine(tests[1][2]); // 70
Console.WriteLine(tests[2].Length); // 1Common mistakes and fixes
- Starting the count at 1: the first item is [0]. The last is [Length - 1] or [^1].
- Expecting an array to grow: arrays have a fixed size. When you need to add and remove items, use List<T> (module 6).
- Using a jagged array's inner array before creating it: tests[0][0] when tests[0] is null throws NullReferenceException.
- Mixing up [1..3]: it gives items 1 and 2 only. The end index is not included.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Arrays: one name, many values · 1/7
In this lesson you will store many values in one array.
Prefer a video by a teacher? Find free videos on “C# arrays tutorial index range 2D jagged array beginners” on YouTube ↗
In real life: Class topper and average for a school report
A school in Lucknow keeps the maths marks of a section in an array. The teacher needs the class average, the highest mark and the top three marks for the notice board.
int[] maths = { 67, 88, 92, 45, 79, 95, 81 };
int total = 0, highest = maths[0];
foreach (int m in maths)
{
total += m;
if (m > highest) highest = m;
}
int[] sorted = (int[])maths.Clone();
Array.Sort(sorted);
int[] topThree = sorted[^3..];
Console.WriteLine($"Average: {(double)total / maths.Length:F1}");
Console.WriteLine($"Highest: {highest}");
Console.WriteLine($"Top three: {string.Join(", ", topThree)}");Practice (0/4 done)
int[] a = { 5, 10, 15, 20 }; What is a[2]?
int[] a = { 5, 10, 15, 20 }; What does string.Join(" ", a[1..3]) give?
What does this print? int[] a = { 1, 2, 3 }; int[] b = a; b[2] = 30; Console.WriteLine(a[2]);
Daily temperatures for a week in Jaipur are 31, 34, 36, 33, 38, 35, 32. Write a program that prints the hottest day number (1 to 7), the average with one decimal, and how many days were above 34.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Strings: methods, interpolation, verbatim and raw stringsArrays, strings and null · same module
- StringBuilder and string performanceArrays, strings and null · same module
- null, nullable types and null-safe operatorsArrays, strings and null · same module
- 2D arrays and classic array algorithmsC Programming (from zero to systems) · Functions and arrays
- ArraysJava Programming (Core to Spring Boot) · Arrays and strings
- Two-dimensional arrays and array algorithmsJava Programming (Core to Spring Boot) · Arrays and strings
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the index of the last item in an array of length 8?
Answer: 7
Indexes go from 0 to Length - 1.
What does new int[3] contain at first?
Answer: 0, 0, 0
Arrays are filled with the type's default value: 0 for int.
What does Array.IndexOf return when the value is not found?
Answer: -1
-1 means "not found" for IndexOf methods.
int[,] g = new int[3, 4]; What is g.Length?
Answer: 12
Length of a 2D array is the total number of cells: 3 x 4 = 12.
What does Console.WriteLine(new int[] { 1, 2 }); print?
Answer: System.Int32[]
Arrays do not print their contents; you see the type name. Use string.Join.
In a function parameter for a 2D int array with 4 columns, which is valid?Related
Answer: int g[][4]
All dimensions except the first are required.
How do you get the length of an array arr?Related
In int[][] t = new int[3][5]; what is t.length and t[0].length?Related
Answer: 3 and 5
First dimension rows (3), second columns (5).
What is the index of the LAST element of an array of size 10?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Arrays, strings and null” before its exam: Strings: methods, interpolation, verbatim and raw strings, StringBuilder and string performance, null, nullable types and null-safe operators.
- Module 3 exam: Arrays, strings and null · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Classes and objects. 43 topics left in the course before the final exam.
← Previous: Parameters in depth: optional, named, ref, out, params, overloading