A Guide to C++ Arrays
In C++, an array is a data structure that contains an ordered list of elements. Each element within an array is called an item, which can be altered or removed.
Arrays play an important role in programming because they allow developers to store similar values in one variable. For instance, an array could contain a list of sneakers in your sneaker collection, or an array could contain a list of your favorite coffee shops.
This tutorial will discuss, with reference and examples, the basics of C++ arrays, how to declare and initialize an array, and how to access the contents of an array in C++. By the end of reading this tutorial, you’ll be an expert at working with C++ arrays.
C++ Arrays
Arrays, or dimensional arrays, are used to store multiple values which have the same data type in one variable. This is more efficient than declaring separate variables to store each individual value and enhances the readability of a program.
A few examples of what an array could be used to store include:
- A list of books in a book collection.
- A list of ingredients in a recipe.
- A list of the phone numbers of everyone who has been called up to support a political campaign.
Lists store data of one specific type in C++. So, a list could store a list of integers, floats, or another type of data. Once an array has been declared, its type cannot be changed.
Declare a C++ Array
To get started working with arrays in C++, we first have to understand how to declare an array. Declaring an array is the process of telling our program that an array should exist, and instructing our code on how many values the array should store.
Here’s the syntax for declaring a C++ array:
dataType arrayName[size];
Let’s walk through an example to demonstrate how to declare a C++ array. Suppose we are building an app which stores the ranking scores for a specific dish that are submitted by a panel of five judges at a local baking competition. We want to create an array that stores five values — one score per judge.
We could declare such an array using this code:
int scores[5];
In our code, we declared an array called scores which stores five integer values. We specified the number of values the array can store in square brackets.
Now that we know how to declare an array in C++, we can discuss how to initialize an array.
Initialize a C++ Array
Initializing an array refers to assigning an array its initial values. In C++, there are two approaches you can use to initialize an array. The first approach is to initialize an array during declaration, and the second is to initialize an array after declaration.
Let’s return to the baking example from earlier. Suppose you already know what scores you want to store in your array when you declare the array. If this is the case, you may want to initialize your array during declaration.
You could use the following code to declare an array and initialize it with the scores submitted by judges for a dish at a baking competition:
int scores[5] = {8, 7, 6, 9, 8};
Alternatively, you can initialize an array after declaration. This is a common approach used to initialize an array in situations where you need to set the values to be stored in an array later in your program.
Let’s say that you wanted to declare an array named scores at the start of your program. This array stores the scores submitted by the judges at the baking competition. You then want to add the judges’ scores in later. You could use the following code to accomplish this task:
int scores[5]; // Your code here int scores[] = {8, 7, 6, 9, 8};
In this example, we first declare an array named scores which can store five values. Then, later in our program, we initialize it with a list of values.
Access C++ Array Elements
Lists in C++ are ordered sequences of items, and each item in a list can be referenced individually, or as part of the whole list.
Each item in a list is assigned an index number, starting with 0, which can be used to access that specific item.
Suppose we have a list called judges which stores the names of the judges who are on our panel for the baking competition. Here is our variable which stores our judges’ names:
string judges[5] = {'Mary', 'Henry', 'Joshua', 'Suhail', 'Louise'};
This array contains five values, and each value has its own index number. The index number assigned to each item in the judges array is as follows:
Mary | Henry | Joshua | Suhail | Louise |
0 | 1 | 2 | 3 | 4 |
Mary, the first name in our list, has the index value 0. Louise, the last name in our list, has the index value 4. Now suppose we wanted to retrieve Suhail’s name from our list. We know that the index number associated with that name is 3. We could use the following code to retrieve his name from the list:
string judges[5] = {'Mary', 'Henry', 'Joshua', 'Suhail', 'Louise'}; cout << judges[3];
Our code returns: Suhail
.
Similarly, we can use indexing to change the values of an element of the array. Suppose that Joshua dropped out of the panel and has been replaced with Alexis. Joshua’s name is stored at the index position 2, which means that we need to replace the name at index value 2 in our list.
We could use the following code to accomplish this task:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
string judges[5] = {'Mary', 'Henry', 'Joshua', 'Suhail', 'Louise'}; judges[2] = "Alexis";
The name Joshua in our array, which was stored at index position 2, has been replaced with Alexis.
It’s worth noting that when you’re working with index values, you can only access index values in the range of the list. So, if your list has 10 values, you can only use index numbers between 0 and 9 (remember, lists are indexed starting from 0). If you try to retrieve or add a value at the 11th position, for instance, an error will be returned.
C++ Array Example
Let’s walk through a more advanced example to demonstrate arrays in action in C++. We’ll return to the baking competition for this example.
Suppose we want to create a program that accepts user input and allows our judges to submit their scores for a particular dish in the baking competition and calculates the total score. We could use the following code for this purpose:
#include <iostream> include namespace std; int main() { int scores[5], total = 0; for (int i = 0; i < 5; ++i) { cout << "Enter score: "; std:cin >> scores[i]; total += scores[i]; } cout << "Total score: " << total; }
Here’s the result of our code when we insert five scores:
Enter score: 9 Enter score: 8 Enter score: 7 Enter score: 8 Enter score: 9 Total score: 41
As you can see, our program has accepted user input for five scores, and has added up those scores to calculate a total value. Let’s break down our code.
First, we declare an array called scores which can hold five values, and a variable called total which keeps track of the total score earned by a dish in the competition.
Next, we initialize a for loop which runs five times. This for loops prints Enter score:
to the console and requests user input. This score is then added to the scores array at index position i, where i is the variable that keeps track of how many times the loop has executed. The score is then added to the total variable.
At the end of our program, the message Total score:
, followed by the value stored in total, is printed to the console. In our example from earlier, total was equal to 41, so our program printed Total score: 41
.
Conclusion
Arrays are used in C++ to store similar values in one variable. For instance, an array could store a list of your favorite bands, or a list of coffees sold at a local cafe.
This tutorial discussed, with reference to examples, how to declare and initialize an array in C++, how to access items in an array, and how arrays are indexed. Now you have the information you need to start working with C++ arrays like a professional!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.