Array Basics C++
Array Basics C++
What Is an Array?
Before we discuss vectors, we will first learn about arrays, a simpler form
of a vector. An array is a data structure that stores a collection of data such
as ints, doubles, strings, etc. This data is often referred to as the array’s
elements. Being able to store elements into an array helps reduce the
amount of time needed to declare and initialize variables. For example, if
you wanted to store the ages of all family members in your household, you
would typically have to declare and initialize integer variables and values
for each family member. Copy the code below into the text editor on the
left and then click the TRY IT button to see the output. You can also click on
the ++Code Visualizer++ link underneath to see how the program runs
behind the scenes.
Code Visualizer
challenge
Code Visualizer
Array Creation
To avoid the repetitive task of declaring and initializing multiple variables,
you can declare an array and directly assign values or elements into that
array like below.
Code Visualizer
Specify the data type that the array will store (i.e. int).
Declare the variable name for the array (i.e. ages) followed by empty
brackets [] followed by the assignment symbol =.
Elements assigned to the array are separated by commas , and enclosed
within curly braces {}.
Additional information
If you used the Code Visualizer, you’ll notice that the array variable ages
refers to all of the elements as a collection. An array is considered to be a
collection that bundles all of the data that it holds.
Alternatively, you can create an array without any elements in which you
will need to declare and specify the array variable name and size before
you can assign elements to the array.
int ages[5];
Specify the data type that the array will store (i.e. int).
Declare the variable name for the array (i.e. ages) followed by the
number of elements you want the array to hold within brackets (i.e.
[5]).
Additional information
Note that when you declare an array without initializing any elements, the
system will still reserve enough memory for the array to hold the specified
number of elements. This means that you can initialize elements within the
array later on.
Array Details
If an element within an array has not been initialized yet, printing it will
cause the system to output random memory data. Random memory data
is often generated when array elements are not initialized.
int ages[5];
cout << ages[0] << endl;
Note that ages[0] in the example above refers the element at index 0, also
known as the first position within the array. Currently, the element at the
first position is not initialized so printing the first element will only output
random memory data. In fact, the same will happen if you try to print any
other elements within the array. Additionally, all elements within the array
must be of the same type. If you try to store a string within an integer array,
or a double within a boolean array, you will get an error message.
challenge
IMPORTANT
When you create an array in C++, you must specify the number of
elements that you expect the array to hold. Otherwise, you will get an
error.
P.O. Boxes at the postal office are symbolically similar to arrays. Each row
of P.O. Boxes is like an array, except each box can only store one item
(element) and each item within that row must be of the same type
(i.e. integers).
.guides/img/ArrayElementsIndices
Accessing an Array
Array Access
To access and print array elements, you need to know their position. The
position at which an element is stored is called its index. For example,
names[0] refers to the first element in the array called names. Array indices
always start at 0 and increment by 1 with each element that comes next.
Due to this, numbers[4] refers to the fifth element in the array, not the
fourth.
challenge
important
IMPORTANT
You may have noticed that printing the names array without specifying
an index resulted in an output that included a mixture of numbers and
letters. This occurs because printing an array actually prints its
memory location, not its elements. You’ll learn how to print all
elements in an array without having to specify all of their indices on a
later page.
challenge
IMPORTANT
Here are some key points to keep in mind when working with arrays:
If you do not initialize any elements, printing the elements will only
result in random memory data.
If you try to access an element position that is not valid (i.e. the
second element in the integers array), the system will also output
random memory data.
Elements must be of the same type as the array. The only exception
is that integers can be expressed as doubles and can therefore be
put into a double array.
.guides/img/ArrayExceptions
Modifying an Array
Array Modification
To modify an element within an array, simply find the index at which that
element is stored and assign a new value to it.
Code Visualizer
challenge
Code Visualizer
cout << family[0] << " " << age[0] << endl;
cout << family[1] << " " << age[1] << endl;
cout << family[2] << " " << age[2] << endl;
cout << family[3] << " " << age[3] << endl;
Code Visualizer
challenge
Code Visualizer
important
IMPORTANT
Since the integer array above was created without any initialization,
random memory data were populated as elements within the array at
first. Then by setting the array indices to specific values, you were able
to modify the array to include the appropriate age for each family
member.
Iterating an Array
Array Iteration
Though we can add many elements to our array, printing each of them can
get quite tedious. For example, if we have 10 names of friends in our array,
we would need to specify each of their array index to print them.
Luckily, we can use loops which we had learned previously to help us with
this process. To print out all of our friends’ names without repeating the
print statement ten times, we can use a for loop to iterate 10 times.
important
IMPORTANT
Did you notice that the print statement above includes i as the index
for friends? We do this because i will take on the values specified by
the for loop. The loop starts at 0 and increments by 1 until it reaches 9
(not including 10). Thus, friends[0] will print, then friends[1], so on
and so forth until friends[9] is printed. Then the loop ends.
Array Size
To make the iteration process easier, we can use the sizeof() operator to
determine how many elements are in our array. To use sizeof(), just call it
by using the keyword sizeof followed by the array name within
parentheses ().
Unfortunately, the sizeof() operator does not determine the number of the
elements within an array. Instead, sizeof() calculates the size of the array
in bytes. In C++, a string takes up 32 bytes and since there are 10 string
elements in the array, the size of the array in bytes is 320.
challenge
challenge
IMPORTANT
One of the main differences between a regular for loop and an
enhanced for loop is that an enhanced for loop does not refer to any
index or position of the elements in the array. Thus, if you need to
access or modify array elements, you cannot use an enhanced for
loop. In addition, you cannot use an enhanced for loop to iterate
through a part of the array. Think of an enhanced for loop as an all-or-
nothing loop that just prints all of the array elements or nothing at all.
Also note that the iterating variable type must match the array type.
For example, you cannot use for (int i : friends) since friends is a
string array and i is an integer variable. Use for (string i : friends)
instead.
Helpful Array Algorithms
Array Algorithms
In addition to being used with loops, arrays can also be used with
conditionals to help with tasks such as searching for a particular element,
finding a minimum or maximum element, or printing elements in reverse
order.
challenge
Sample Solution
string cars[] = {"Corolla", "Camry", "Prius", "RAV4",
"Highlander"};
string Prius = "A Prius is not available.";
cout << "The lowest grade is " << min << endl; //print lowest
element
challenge
Sample Solution
int grades[] = {72, 84, 63, 55, 98};
int max = grades[0];
cout << "The highest grade is " << max << endl;