What Arrays Solve
A quick review of what arrays do well, fast access by position, one name for a group, and easy looping, before meeting their limits.
Apprentice · C# · Updated
After this lesson you can
- Explain what arrays do well, such as fast access by index and easy looping
Key takeaways
- An array stores its elements side by side, so reaching any element by its index takes the same short time, whether it's the first or the ten-thousandth.
- An array keeps related values under one name, so you can hand the whole group to a method in one argument.
- A loop can visit every element of an array in order, to search, add up, change or print them.
Array.Sortputs an array's elements in order: alphabetical for text, smallest first for numbers.- When you know how many values you have, and that number won't change, an array is a good fit.
You've used arrays to hold groups of values: scores, names, prices. Before meeting C#'s other collections, it's worth being clear about what arrays do well, because the others build on them.
Fast access by position
An array stores its elements side by side, in one block of the computer's memory. To find element 10,000, the computer doesn't search: it works out exactly where it is from the index, and goes straight there. Reaching any element by its index takes the same short time, whether it's the first or the ten-thousandth.
int[] attendance = new int[10_000];
attendance[9_999] = 92_746;
Console.WriteLine(attendance[9_999]);
92746
(Underscores in a number, as in 10_000, are only there to make it easier to read. C# ignores them.)
One name for a group
An array keeps related values together under one name. You can hand the whole group to a method in one argument, instead of a long list of separate variables:
int[] quarterScores = { 12, 14, 6, 7 };
Console.WriteLine( quot;Final score: {Total(quarterScores)}");
int Total(int[] scores)
{
int total = 0;
foreach (int score in scores)
{
total += score;
}
return total;
}
Final score: 39
Easy to loop over
Because every element has a numbered place, a loop can visit them all, in order, to search, add up, change or print them. Many everyday algorithms, such as finding the largest value or sorting, are designed around exactly this.
string[] teams = { "Ohio State", "Georgia", "Clemson", "Alabama" };
Array.Sort(teams);
foreach (string team in teams)
{
Console.WriteLine(team);
}
Alabama
Clemson
Georgia
Ohio State
Array.Sort puts an array's elements in order: alphabetical for text, smallest first for numbers.
Check yourself
1 question to try on the lesson page.
So what
When you know how many values you have, and that number won't change, an array is fast, simple and hard to beat.