Arrays

Sometimes it can be useful to group multiple pieces of data together, and arrays let us do just that.

For example, if we wanted to keep track of multiple people’s ages, it would be tedious to write code like below:

#include <iostream>

int main() {
    int person1Age = 5;
    int person2Age = 15;
    int person3Age = 17;
    int person4Age = 8;
    std::cout << "Person 1 is " << person1Age << ".\n";
    std::cout << "Person 2 is " << person2Age << ".\n";
    std::cout << "Person 3 is " << person3Age << ".\n";
    std::cout << "Person 4 is " << person4Age << ".\n";
    return 0;
}

That just requires a bunch of copy-pasting, which should really be avoided when possible (Why? Generally, doing this makes it harder to modify code later on. For example, if I wanted to change the printed message above to “Person X is Y years old.”, I would need to add the words “years old” four separate times. While this is definitely doable, it’s really not ideal, and it can become a severe issue for larger projects.)

Before applying an array to the code above, let’s take a look at how arrays really work. Here’s what all the ages look like put together in an array:

int ages[] = {5, 15, 17, 8};

We use the data type int because each value in the array is an integer. Two square brackets “[” and “]” are also needed immediately following the array name (“ages” in this case). These brackets indicate that “ages” is in fact an array. Optionally, they can also contain the length of the array (4, in this case, because of the 4 ages) like this:

int ages[4] = {5, 15, 17, 8};

To set the array’s values (called “elements”), we use an equals sign (like for other variables) followed by curly braces containing a list of all the elements separated by commas. Now, how can we get these elements from the array? See below!

Getting an Array’s Elements

#include <iostream>

int main() {
    int ages[] = {5, 15, 17, 8};
    std::cout << ages[0] << "\n";
    return 0;
}

To get an array’s elements, just use square brackets containing the “index” of the element you want. All the “index” is is a number representing how far from the beginning of the array an element is located. With the ages array, the element at index 0 is 5, the element at index 1 is 15, and so on. Always remember that, in C++, array indices start at 0.

In the code above, we print the element of the ages array located at index 0 (because 0 is the number inside the square brackets). Therefore, the number 5 is printed.

If we want to easily print all of an array’s elements, we can use a for loop:

#include <iostream>

int main() {
    int ages[] = {5, 15, 17, 8};
    for (int i = 0; i < 4; i++) {
        std::cout << "Element at index " << i << ": " << ages[i] << "\n";
    }
    return 0;
}

Modifying Arrays

We can also modify elements in an array in a similar fashion:

#include <iostream>

int main() {
    int ages[] = {5, 15, 17, 8};
    ages[2] = 12;
    std::cout << ages[2] << "\n";
    return 0;
}

Just put the index of the element you want to modify in square brackets and set the element equal to some new value.

Fixing the “Copy-Paste” Problem

Now, let’s go back to that first code example, which looked like this:

#include <iostream>

int main() {
    int person1Age = 5;
    int person2Age = 15;
    int person3Age = 17;
    int person4Age = 8;
    std::cout << "Person 1 is " << person1Age << ".\n";
    std::cout << "Person 2 is " << person2Age << ".\n";
    std::cout << "Person 3 is " << person3Age << ".\n";
    std::cout << "Person 4 is " << person4Age << ".\n";
    return 0;
}

By putting all of the ages in a single array and using a for loop to print every age, this code can look a lot cleaner:

#include <iostream>

int main() {
    int ages[] = {5, 15, 17, 8};
    for (int i = 0; i < 4; i++) {
        std::cout << "Person " << i + 1 << " is " << ages[i] << ".\n";
    }
    return 0;
}

Nice!

Creating Empty Arrays

Creating an empty array is very similar to creating an array assigned to a list of elements. Just know that, when doing so, the size of the array must be included inside the square brackets, as shown here:

int main() {
    int numbers[10];
    for (int i = 0; i < 10; i++) {
        numbers[i] = i;
    }
    return 0;
}

To initially set every element of the numbers array to zero you can first set it equal to {0}:

#include <iostream>

int main() {
    int numbers[10] = {0};
    for (int i = 0; i < 10; i++) {
        std::cout << numbers[i] << "\n";
    }
    return 0;
}

Without doing so, the initial values of the array’s elements could be any number, although this usually isn’t an issue (since they would be set a new value later on anyways).

Try it: Remove the “ = {0}” from the program above and see what numbers are printed to the screen. I got:

8
0
4199705
0
8
0
11
0
15672304
0

Limitations

There are some limitations with arrays in C++:

  • An array’s size can never be changed. In other words, elements cannot be added to or removed from an array.
    • In the next page of this guide we’ll look at vectors, which are very similar to arrays but allow for adding and removing elements.
  • Be very careful to only use indices that fall within an array.
    • If your code contains an array with 4 elements, for example, then never expect good results when trying to access array[4] or greater, and be sure to never use negative indices. Doing so can cause you to access memory that you shouldn’t mess with, which may lead to your program crashing.
    • You will not get warnings if you use indices that are out of an array’s bounds, and your program may even work sometimes when using an out-of-bounds index. Therefore, it’s up to you to make sure this never happens.
  • All of an array’s elements cannot be modified at once. For example, the code below would not work:
#include <iostream>

int main() {
    int ages[] = {5, 15, 17, 8};
    ages = {6, 12, 2, 20};
    return 0;
}

Challenge Problem

Write a program that sorts the array {23, 6, 12, 10, 18, 4} from its smallest to its largest elements. After being sorted, print each element of the array to the screen. (The final array should be {4, 6, 10, 12, 18, 23}.)

To sort the array, use the bubble sort algorithm. A little video on the algorithm can be found here. Just note that, while bubble sort is one of the easiest ways of sorting an array, much faster algorithms exist.

If you get stuck, check out my solution here.