0% found this document useful (0 votes)
3 views

Comp 1601 - Arrays Notes

Uploaded by

vc89bq2c6x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Comp 1601 - Arrays Notes

Uploaded by

vc89bq2c6x
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

15.

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.

15.1 The Need for an Array

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;

If there were two students enrolled, two variables would suffice:

int mark1;
int mark2;

If there were five students enrolled, five variables would be necessary:

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;

To display the marks, the following code can be used:

cout << "Marks obtained by the students: " << endl;


cout << mark1 << endl;
cout << mark2 << endl;
cout << mark3 << endl;
cout << mark4 << endl;
cout << mark5 << endl;

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.

15.2 Declaring an Array

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 name marks

array elements marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]

Figure 15.1: Array with 10 Memory Locations to Store Marks

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:

int marks [10];

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:

char name [20];

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.

15.3 Identifying an Array Element

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,

• Giving it a value using an arithmetic expression


• Inputting its value from the keyboard using a cin statement
• Displaying its value on the monitor using a cout statement
• Using its value in an arithmetic expression
• Using its value in a relational expression
• Reading its value from a file
• Writing its value to a file

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.

15.5 Assigning a Value to an Array Element using an Arithmetic Expression

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:

marks [0] = 75;

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:

marks [0] = 75 + (75 * (bonus/100.0));

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:

marks [0] = mark + (mark * (bonus/100.0));

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:

for (i=0; i<10; i=i+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:

for (i=0; i<10; i=i+1) {


marks [i] = 0;
}

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.

15.6 Inputting the Value of an Array Element from the Keyboard

Consider the following input statement, where num is an integer variable:

cin >> num;

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]:

cin >> 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):

cin >> marks [0];


cin >> marks [1];
.
.
.
cin >> marks [9];

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:

for (i=0; i<10; i=i+1) {


cout << "Please enter mark for student " << i << ": ";
cin >> marks[i];
}

15.7 Displaying the Value of an Array Element on the Monitor

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:

cout << marks [5] << endl;

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:

for (i=0; i<10; i=i+1) {


cout << marks[i] << endl;
}

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:

for (i=9; i>=0; i=i-1) {


cout << marks[i] << endl;
}

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:

for (i=start; i<=end; i=i+1) {


cout << marks[i] << endl;
}

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.

15.8 Using the Value of an Array Element in an Arithmetic Expression

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:

highest = marks [0];

We can even add 5 to element 2 of the array as follows:

marks [2] = marks [2] + 5;

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:

for (i=0; i<10; i=i+1) {


marks [i] = marks [i] + 5;
}

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:

marks [5] >= 50

This relational expression can be used in an if-else statement as follows:

if (marks [5] >= 50)


cout << "Student has passed." << endl;
else
cout << "Student has failed." << endl;

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:

for (i=0; i<10; i=i+1) {


if (marks[i] >= 50)
cout << "Student " << i << " has passed." << endl;
else
cout << "Student " << i << " has failed." << endl;
}

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:

inputFile >> marks [3];

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:

for (i=0; i<10; i=i+1) {


inputFile >> marks[i];
}

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:

outputFile << marks [3] << endl;

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:

for (i=0; i<10; i=i+1) {


outputFile << marks[i] << endl;
}

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];

a. How many elements does the array contain?


b. What is the range of subscripts in the array?
c. Assign 34 to the first location of the array.
d. Assign 32 to the last location of the array.
e. Display the value in the second location of the array.

2. Write the statements to declare each of the following:


a. A floating-point array of size 25.
b. A character array of size 50.
c. A string array of size 100.

3. Given the following array:

12 56 89 20 69 1 101 5 89
num 0 1 2 3 4 5 6 7 8

a. How many elements can be stored in the array num?


b. What is the value in location 5 of the array?
c. 20 is in what location of the array?
d. What is the output produced by the following statement?
cout << num [7] << endl;

e. What is the value of sum after the following code is executed?


int sum;
sum = num [3] + num [4];

4. What size would you recommend for the following arrays?


a. An integer array to store the amount of road accidents on each day of a given year.
b. A double array to store the price of a company’s stock on each day of a given month.
c. An integer array to store the population of each country in the world.
d. A character array to store the last name of a student.

12

You might also like