Arrays in C#

Arrays

The Crash Course

  • Arrays store collections of related objects of the same type.
  • To create an array, you use the square brackets and the new keyword: int[] scores = new int[10];.
  • You can also create arrays by giving specific values: int[] scores = new int[] { 1, 2, 3, 4, 5 };
  • You can access and modify values in an array with square brackets as well: int firstScore = scores[0]; and scores[0] = 44;
  • Indexing of arrays is 0-based, so 0 refers to the first element in the array.
  • You can create arrays of arrays: int[][] grid;
  • You can also create multi-dimensional arrays: int[,] grid = new int[5, 4];
  • You can use the foreach loop to easily loop through an array and do something with each item in the array: foreach(int score in scores) { /* ... */ }

Introduction

In this tutorial, we'll take a look at arrays. Arrays are powerful features of any programming language, that allow us to store collections or groups of related objects altogether. We'll talk about how to create them and use them, go through a few examples of how to work with them, how to make multi-dimensional arrays (what they call a matrix in the math world), and then wrap up with a discussion of the last type of loop that we didn't discuss in the previous tutorial on looping.

What is an Array?

An array is a way of keeping track of a list or collection of many related things altogether. Imagine, for instance, that you have a high score board in a game with up to 20 high scores on it. Using what we know, you could easily create one variable for every score you want to keep track of. Something like this:

int score1 = 100;
int score2 = 95;
int score3 = 92;
// ...

That's one way to do it. But what if you had 10,000 scores? Suddenly, creating that many variables to store scores is overwhelming.

This brings us to arrays. Arrays are perfect for keeping track of things like this since they could store 20 scores or 10,000 scores in a way that is both easy to create and easy to work with once they're created.

Working with Arrays

Creating an array is very similar to creating any other variable. You give it a type and a name, and you can initialize it at the same time if you want. You create an array using the square brackets ([ and ]).

int[] scores;

This would create an array containing a number of ints. To create a new array and assign it to a variable, you will use the new keyword and specify the number of elements that you'll have in the array:

int[] scores = new int[10];

In the earlier example, we had not yet assigned a value to an array. In this second example, our array now exists and has 10 items in it.

At this point, we can now assign values to specific spots in the array. To refer to a specific spot in the array, we will use the square brackets again, along with what is called a subscript, or an index, which is a number that tells the computer which of all of the "elements" (things in an array) to access. For example, to get the first element in an array, we would use the following line of code:

int firstScore = scores[0];

One thing you see here is very important. It is very important to remember that array indexing is 0-based! The first item in an array is the number 0! I know it seems kind of strange, and I won't go into the details right now, but there's a very good reason for this, and many programming languages do it. If you ever get this wrong, you'll run into what is called off-by-one errors because you're on the wrong number.

You can access any value in an array by using the same technique:

int fourthScore = scores[3];
int eighthScore = scores[7];

If you try to access something beyond the end of the array (for example, scores[50] in an array with 10 items in it), your program will crash, telling you the index was out of the bounds of the array.

You can also assign a value to an array using the same basic technique:

int[] scores = new int[10];
 
scores[0] = 100;
scores[1] = 95;
scores[2] = 92;
// ...

There are a couple of other ways of initializing an array that are worth discussing here. You can also create an array by giving it specific values right from the get-go, by putting the values you want inside of curly braces ({ and }) and separated by commas:

int[] scores = new int[10] { 100, 95, 92, 87, 55, 50, 48, 40, 35, 10 };

When you create an array this way, you don't even need to state the number of items that will be in the array (the '10' in the square brackets, in this case). You can leave that out:

int[] scores = new int[] { 100, 95, 92, 87, 55, 50, 48, 40, 35, 10 };

Using the Length property, we can also tell how long an array is. (Er… we haven't really talked about properties yet, but we will soon enough. For now, all you need to know is that it is easy to do, and I'll show you how….)

int totalThingsInArray = scores.Length; // See, I told you it would be easy...
Console.WriteLine("There are " + totalThingsInArray + " things in the array.");

Some Examples with Arrays

Now that we know the basics of how arrays work, let's look at a couple of short examples of how you might use arrays.

Minimum Value in an Array

In our first example, we'll calculate the minimum value in an array using a for loop.

The basic process will require looking at each item in the array in turn. We'll create a variable to store the value that we know is the minimum we've looked at. As we go down the list of numbers in the array, if we find one that is less than our current known minimum, we'll reassign the known minimum to the new value.

int[] array = new int[] { 4, 51, -7, 13, -99, 15, -8, 45, 90 };
 
int currentMinimum = Int32.MaxValue; // We start really high so that any element in the array will be lower than this.
 
for(int index = 0; index < array.Length; index++)
{
    if( array[index] < currentMinimum )
    {
        currentMinimum = array[index];
    }
}
 
// At this point, currentMinimum contains the minimum value in the array.

Average Value in an Array

Let's try a similar but different task: finding the average value in an array. We'll follow the same basic pattern as in the last example, but this time, we're going to total up the numbers in the array. When we're done doing that, we'll divide by the total number of things in the array to get the average. (In case you don't remember from math classes, the average of a group of numbers is the sum/total of all of the numbers put together, divided by the number of values there were.)

int[] array = new int[] { 4, 51, -7, 13, -99, 15, -8, 45, 90 };
 
int total = 0;
 
for (int index = 0; index < array.Length; index++)
{
    total += array[index];
}
 
float average = (float)total / array.Length;

Arrays of Arrays and Multi-Dimensional Arrays

You can have arrays of basically anything. ints, floats, bools. You can even have arrays of arrays! (Or arrays of arrays of arrays!) This is one way that you can create a matrix. (A matrix is simply a grid of numbers, with a certain number of rows and a certain number of columns. Kind of like an Excel spreadsheet, for example.)

To create an array of arrays, you use the following notation:

int[][] matrix = new int[4][];
matrix[0] = new int[4];
matrix[1] = new int[5];
matrix[2] = new int[2];
matrix[3] = new int[6];
 
matrix[2][1] = 7;

Notice that each of my arrays within the main array has a different length. You could, of course, make them all the same length (there's a better way to do this; we'll see that in a second). When each array within a larger array has a different length, it is called a jagged array. It is often called a square array or a rectangular array if they're all the same length. You can string as many of these together as you want.

There's another way to work with arrays of arrays, assuming you want a rectangular array (which is almost always the case). This is called a "multi-dimensional array".

To do this, you put multiple indices (the plural of index) inside of one set of square brackets like this:

int[,] matrix = new int[4, 4];
matrix[0, 0] = 1;
matrix[0, 1] = 0;
matrix[3, 3] = 1;

Support for multi-dimensional arrays, by the way, is one feature that both C++ and Java (both very similar to C# in many ways) are missing (though they both support the jagged arrays we already talked about).

The foreach Loop

To wrap up our discussion of arrays, let's return to what we discussed in the previous tutorial about loops. There's one final loop type that works well when you're doing stuff with arrays. This type of loop is called the foreach loop (as in "do this particular task for each element in the array).

To use a foreach loop, you use the foreach keyword with an array, specifying the name of the variable to use inside of the loop:

int[] scores = new int[10];
 
// Populate data and maintain it as your program runs. The below is just an example.
scores[0] = 42;
scores[5] = -1;
 
foreach (int score in scores)
{
    Console.WriteLine("Someone had this score:  " + score);
}

You can use the score variable inside the loop.

One key thing to note here is that inside the loop, you have no way of knowing what index, specifically, you are currently at. (You don't know if you are on scores[2] or scores[4].) In many cases, that's no big deal. You don't care what index you're at, you just want to do something with each item in the array. If you need to know, you'll have to use a for loop instead:

int[] scores = new int[10];
 
// Populate data and maintain it as your program runs. The below is just an example.
scores[0] = 42;
scores[5] = -1;
 
for(int index = 0; index < scores.Length; index++)
{
    int score = scores[index];
    Console.WriteLine("Score #" + index + ":  " + score);
}

What's Next?

That wraps up our discussion on arrays in C#. Arrays can be very useful in all sorts of situations. In fact, every sophisticated program will be able to put them to good use.

Moving on, our next topic will be to take a look at enumerations, which are a nifty little language construct that makes it easy to create your own kind of variables, in a sense.