Comp 1601 - Arrays Notes
Comp 1601 - Arrays Notes
Arrays
In this chapter, we introduce a new way to store data in a program known as an array. An array can be
used to store and manipulate a group of related data as if it were one unit. The data must be of the
same type. All the elements of the group are referred to by the same name. Because of this, an array is
often used to store and manipulate a large amount of similar data in a program.
Consider the problem of storing the marks of the students registered for a course. If there was one
student enrolled, a single variable would suffice:
int mark;
int mark1;
int mark2;
int mark1;
int mark2;
int mark3;
int mark4;
int mark5;
To input the marks obtained by the five students at the keyboard, the following code can be used:
cout << "Please enter the marks obtained by the five students: ";
cin >> mark1 >> mark2 >> mark3 >> mark4 >> mark5;
1
To find the average mark of the five students, the following code would be required:
float average;
average = (mark1 + mark2 + mark3 + mark4 + mark5) / 5.0;
As can be seen, it is starting to get rather cumbersome to declare five variables, input the values of the
variables, display the values of the variables on the monitor, calculate the average, etc.
Now, suppose that there are 10 students enrolled. We must declare 10 variables and modify the input
and output statements as well as the statement that calculates the average. What if 100 students were
enrolled in the course? Surely, there must be a better way to declare the variables, assign values to
them, display their values, etc.
An array makes it possible to store and manipulate a collection of related data as if it were one unit. The
marks of the students enrolled in a course are all integers and thus the marks can be stored in an array.
Figure 15.1 shows an array which contains ten memory locations for the marks obtained by 10 students
enrolled in a course. The memory locations are numbered from 0 to 9. The first location of an array is
always numbered 0.
array locations 0 1 2 3 4 5 6 7 8 9
array elements marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
Just like the variables we have been dealing with so far, an array must be declared before it can be used.
The following statement shows how to declare an array, marks, containing 10 memory locations to store
integer values:
2
The declaration of an array is similar to the declaration of a single integer variable, except that the
square brackets after the variable name indicate that an array is being declared. The actual size of the
array, 10, is specified within square brackets; 10 indicates that the array has the capacity to store 10
integer values.
Arrays can store values of types such as float, double, string, or char. They are declared in a similar
manner to an integer array. To declare an array, name, containing 20 memory locations to store
character values, the following declaration is made:
Once an array is declared to be a certain type, it should not be used to store values of another type. For
example, the name array should not be used to store double values.
An array consists of a group of elements, each of which has the same data type. To perform operations
on the elements of an array, it is necessary to identify each array element separately. An array element
is identified by writing the name of the array, followed by the location of the element in the array,
within square brackets. For example, marks [0] is the first element of the marks array and marks [9] is
the last element (see Figure 15.1). The number within the square brackets (e.g., 0 or 9) is referred to as
an array subscript. Thus, the name of the array, followed by an array subscript enclosed within square
brackets, can be used to identify an element of an array.
Once an array element has been identified, it is treated as a normal variable and can be used anywhere
in a program where a variable is expected. The data type of the variable is the same as the type that was
used to declare the array.
3
15.4 Basic Operations on Arrays
The remaining sections of this chapter show how to perform various operations on an array element.
We will also show how to extend these operations to include all the elements of an array. The
operations on an array element are as follows,
Before discussing the various operations that can be performed on an array element, it is important to
note that declaring an array to be a certain size automatically sets a bound on the subscripts for that
array. For example, if an array is declared to be of size 10, the subscripts can only take on values from 0
to 9. If an array is declared to be of size 25, the subscripts can only take on values from 0 to 24. If an
invalid array subscript is used to identify an array element, unpredictable results may occur. Thus, it is
important to always ensure that the subscript being used to identify an array element is within the
declared bounds of the array.
The assignment operator, =, can be used to assign the value of an arithmetic expression to an array
element. For example, to assign the value 85 to the element at location 0 of the marks array, the
following statement can be used:
4
Suppose we would like to apply an increase of bonus percent when assigning the value to marks [0]. This
can be done as follows:
Next, suppose that the value to be assigned to element 0 is stored in an integer variable, mark. The
assignment statement can be written as follows:
Thus, element 0 of the marks array can be assigned the value of an arithmetic expression of arbitrary
complexity. The same is true for the other elements of the array.
Now, suppose that we would like to store 0 in each element of the marks array. This can be done as
follows:
marks [0] = 0;
marks [1] = 0;
marks [2] = 0;
marks [3] = 0;
marks [4] = 0;
marks [5] = 0;
marks [6] = 0;
marks [7] = 0;
marks [8] = 0;
marks [9] = 0;
This is not much better than when we were using an ordinary variable to store the marks of each
student enrolled in the course. There must be a better way! To find this better way, observe in the code
above how the array subscripts go from 0 to 9 in increments of 1. What programming construct can be
used to generate the sequence of numbers from 0 to 9 in increments of 1?
If you guessed, for loop, you are correct! A for loop can be used to generate all the subscripts (or array
locations from 0 to 9) in increments of 1:
5
The for loop generates all the array subscripts from 0 to 9 as it executes. These are stored in the loop
control variable, i. Therefore, to identify each array element uniquely in each pass of the loop, the name
of the array is written, followed by the array subscript i, enclosed within square brackets:
If the array contains one million elements, a similar statement can be used to assign 0 to all its elements.
The only thing that needs to change is the second section of the for statement, i < 1000000. Thus, using
a for loop to process the elements of an array makes it possible to manipulate a large amount of data
with very little programming effort.
This input statement waits for the user to type an integer at the keyboard and then stores the value in
the variable, num. Similarly, the following statement can be used to store a value typed at the keyboard
in an array element, say, marks [3]:
Now, let’s suppose that we would like the user to enter the values of all the array elements at the
keyboard. The following code can be used to store the values entered by the user in each location of the
array (note that the prompt statements are omitted):
6
This is not very efficient, bearing in mind that arrays can be of different sizes which can be arbitrarily
large. As before, a for loop can be used to generate the array locations from 0 to 9 in increments of 1. In
each pass of the for loop, the user enters a value which is then stored in the appropriate array location
identified by the array subscript. This is shown below:
To display the value of a particular element of an array on the monitor, the array element needs to be
identified using the name of the array, followed by the location of the element in square brackets (its
array subscript). For example, to display the value of the element at location 5 in the marks array, the
following cout statement can be used:
To display the values of all the elements in the array, a for loop can be used to generate the array
subscripts from 0 to 9. In each pass of the for loop, the element identified by the array subscript is
displayed on the monitor. The code is as follows:
The elements of the array can be displayed in reverse order by displaying marks [9] first, followed by
marks [8], until marks [0] is reached. This means that the array subscripts should be generated from 9 to
0, decreasing by one each time. This can be arranged by modifying the way in which the for loop
generates the subscripts:
7
Instead of displaying all the elements of the array on the monitor, we can choose to display only the
elements that fall within a certain range. However, we need to tell the for loop what is the starting
subscript (location) and what is the ending subscript (location) of the range. Suppose these values are
stored in the integer variables, start and end, respectively. The following statement can be used to
display the elements from the given range:
Given that the array has 10 elements, it is important to check that start is greater than or equal to 0 and
end is less 10. If this is not the case, the for loop will generate subscripts that identify non-existent out-
of-bound elements. As previously mentioned, this can cause unpredictable errors while the program is
executing.
An array element can be used in an arithmetic expression just like any other variable. For example, if
highest is an integer variable, it can be assigned the value of element 0 of the marks array:
Suppose we would like to increase the value of each element in the marks array by 5. As before, we can
use a for loop to generate the subscripts from 0 to 9. In each pass of the for loop, 5 is added to the array
element identified by that subscript:
8
15.9 Using the Value of an Array Element in a Relational Expression
Suppose we would like to know if the value of element 5 of the marks array corresponds to a pass or a
fail. If the value is greater than or equal to 50, it is a pass; otherwise, it is a fail. Element 5 can be used in
a relational expression that checks if its value is greater than or equal to 50:
We can determine if each student in the marks array has passed or failed by using a for loop to generate
the subscripts from 0 to 9:
Notice that i is now included in the cout statement to indicate the specific array element that is being
displayed.
9
15.10 Reading the Value of an Array Element from a File
Suppose the text file, marks.txt, contains the marks of 10 students enrolled in a course. To read the
values from the file into a program, an ifstream object must be declared and connected to the file as
follows:
ifstream inputFile;
inputFile.open ("marks.txt");
Once the file is opened, a value can be read from the file and assigned to an array element such as
marks [3] as follows:
To assign values to all the array elements, the values can be read from the file and assigned to the array
elements using a for loop which generates all the subscripts from 0 to 9:
inputFile.close();
The file must contain at least 10 integer values. Otherwise, errors will occur while the program is
executing.
10
15.11 Writing the Value of an Array Element to a File
Suppose that we would like to store the value of element 3 of the marks array in a text file, results.txt.
An ofstream object must be declared and connected to the file as follows:
ofstream outputFile;
outputFile.open ("results.txt");
Once the file is opened, the value of marks [3] can be written to the file as follows:
To write the values of all the array elements to the file, a for loop can be used to generate the subscripts
from 0 to 9. In each pass of the for loop, the array element identified by the subscript is written to the
file:
outputFile.close();
11
15.12 Exercises
1. An array, temperature, is declared to store the maximum temperature for the month of October:
int temperature [31];
12 56 89 20 69 1 101 5 89
num 0 1 2 3 4 5 6 7 8
12