Module 1 Arrays
Module 1 Arrays
SeeOverview
The variables we have worked with so far can hold only one value at a time. For example, if you declare an
integer variable named testScore to represent a student’s test score, that variable can hold only one test
score.
The fact that the variable testScore can hold only one test score is not a problem so long as that student only
takes one test. However, if the same student takes another test, or another student takes the same test,
where do you store the second test score? If you store the second score in testScore, then you lose the ability
to retrieve the first score from the variable testScore, since that variable can hold only one test score at a
time.
Therefore, if you wanted to keep track of, for example, 100 test scores, your code might look like this:
int testScore1;
int testScore2;
int testScore3;
int testScore4;
int testScore5;
int testScore6;
int testScore7;
int testScore8;
int testScore9;
int testScore10;
Yikes! That’s a lot of code to write. Wouldn’t it be easier just to declare 1 variable that can hold 100 values,
like this:
int testScore[100];
The good news is you can do exactly that, using an array! An array enables you to use a single variable to
store many values. The values are stored at consecutive indexes, starting with zero and then incrementing by
one for each additional element of the array.
Using 1 array variable to store 100 values has many advantages over having to declare 100 separate variables
that can hold only 1 value each. In addition to being a lot less code to write, it is far easier to keep track of 1
variable than 100. Furthermore, and more important that in this chapter, you can use a loop to access each
consecutive element in an array, whereas this is not possible with three separate variables.
● The size and the data type of an array cannot be changed after the declaration. The length of the array is
defined when the array is created and the length of the array is fixed it cannot be changed.
● In arrays, each value is an element and these elements are accessed through an index.
● A series of objects all of which are the same size and type. Each object in an array is called an array
element. For example, you could have an array of integers or an array of characters or an array of
anything that has defined data type.
Arrays can have more than one dimension. A one-dimensional array is called a vector; a two-dimensional array
is called a matrix.
Components of Array
1. Array name – collective name for the array element.
2. Index type – set of subscripts that are used to differentiate one element to another.
3. Base type – data type of array element.
An array is a variable. Therefore, like the other variables , an array must be declared before it can be used.
The syntax for declaring an array is almost identical to the syntax for declaring integers, characters, or other
variables.
int testScore;
By contrast, you would declare an array of three test scores this way:
int testScore[3];
This declaration contains an array of integers. You instead could declare an array of floats, characters, or
strings in the following manner:
Page 2 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
e.g.
float GPA [5];
char grades[7];
string names[6];
While an array may be one of several data types, all the values in a particular array must be of the same
data type. You cannot have an array in which some elements are floats, others are strings, still others are
integers, and so on.
The declaration of both a single variable and an array of variables begins with the data type followed by a
variable name and ending with a semicolon. The only difference between declaring a variable that holds a
single value and an array is that, when declaring an array, the variable name is followed by a number within
square brackets. That number is the array’s size declarator.
The purpose of the size declarator is to tell the computer how much memory to reserve. The size declarator,
combined with the data type of the array, determines how much memory to reserve.
ADVANTAGES OF ARRAYS
● It is easy to sort the data in arrays by using the swapping technique.
● You can randomly access the values of array with the help of array index.
● It provides the code optimization that means less code is required.
● You can retrieve the data from an array easily.
DISADVANTAGES OF ARRAYS
● The main disadvantage of the arrays is the size limit. In this, you can store the fixed size of elements.
ARRAY INDEX
The entire array has only one name. However, you need to be able to refer to individual elements of the array.
You can refer to the individual elements of the array by their position within the array. This position is referred
to as an index or subscript.
The first index in an array is always 0. There are no exceptions. The last index in an array is always 1 less
than the number of elements in the array; again, with no exceptions.
The fact that the first index in an array is 0 instead of 1 is explained by the concept of an offset. An offset
refers to a value added to a base address to produce a second address.
Page 3 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
Figure 10-1 may be helpful in illustrating how offsets work with arrays. This figure shows graphically the result
of declaring a three-element integer array such as int testScore[3]. The base address of an array is the address
where the array begins. In Figure 10-1, the base address of the testScore array is 101.
The address of the first element of the array in Figure 10-1, 101, is the same as the base address of the array
itself. Therefore, the value that would be added to the base address of the array to obtain the address of the
first element of the array is 0, which is the index of the first element of the array.
The address of the second element of the array is the base address of the array, 101, plus 1 times the size of
the data type of the array, 4, which is 101 + (1 × 4), or 105. Similarly, the address of the third element of the
array is the base address of the array, 101, plus 2 times the size of the data type of the array, 4, which is 101 +
(2 × 4), or 109.
Thus, the address of any element of the array is the base address of the array plus the offset, and in turn the
offset is determined by the index of the array multiplied by the size of the array’s data type.
Since the first index in an array must always be 0, the last index in an array must always be 1 less than the
number of elements in the array. If you were counting three numbers, starting at 1, the last element would be
number 3. However, if you are starting at 0 instead of 1, then the last number would be 2, not 3.
Caution: A common beginning programming mistake is to assume the index of the last element of the
array is equal to the number of elements in the array. As you will learn later in this chapter, this can
result in (depending on the compiler) run-time errors or unpredictable results, neither of which is
good.
At this point, we have not assigned a value to any of the elements of the array. The value of each element
likely will be some strange number such as –858993460. As discussed in Chapter 3, the program does its best
to interpret whatever value is at a given memory address, perhaps left over from some other program, but the
resulting output often makes little sense.
Note: If the array variable is declared globally rather than locally, then each element is initialized to a
default value, 0 for numeric data types and the null character for a character array.
Page 4 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
The following program shows how to assign values to an array, one element at a time. The assignment starts
with the first index, 0, and ends with the last index, 2, which is one less than the number of elements, 3. The
program then outputs the array values, one at a time.
#include <iostream>
using namespace std;
int main ()
{
int testScore[3];
cout << "Test score #1: " << testScore[0] << endl;
cout << "Test score #2: " << testScore[1] << endl;
cout << "Test score #3: " << testScore[2] << endl;
return 0;
}
However, this one-element-at-a-time approach has no advantage over the following program, which does
not use an array at all, but just three separate variables:
#include <iostream>
using namespace std;
Page 5 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
int main ()
{
int testScore1, testScore2, testScore3;
cout << "Test score #1: " << testScore1 << endl;
cout << "Test score #2: " << testScore2 << endl;
cout << "Test score #3: " << testScore3 << endl;
return 0;
}
The advantage of an array over using separate variables is the ability to use a loop. This is shown by the
following program:
#include <iostream>
using namespace std;
int main ()
{
int testScore[3];
return 0;
}
Page 6 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
TYPES OF ARRAY
ONE-DIMENSIONAL ARRAYS
type name[size];
ex:
int sample[10];
Index
0 10
1 20
2 50
3 80
4 30
Code: Output:
{ This is sample[4] : 4
int sample[5];
int ctr;
for(ctr=4;ctr>=0;ctr--)
{
sample[ctr] = ctr;
}
for(ctr=4;ctr>=0;ctr--)
{
cout << "This is sample[" << 4 - ctr <<
"] : "
<< sample[ctr] << endl;
}
return 0;
}
Problem #1:
Write a program that will accept 5 input quizzes then displays all the quizzes that you have entered and show
their average as shown below.
Sample I/O:
Enter quiz # 1: 68
Enter quiz # 2 : 96
Enter quiz # 3 : 85
Enter quiz # 4 : 75
Enter quiz # 5 : 82
Your average quiz from 68, 96, 85, 75, 82, is 81.2
Code:
#include<iostream>
using namespace std;
int main()
{
int ctr;
int quiz[5];
float sum=0,ave;
for(ctr=0;ctr<5;ctr++)
{
Page 8 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
cout << "Enter quiz # " << ctr << " : ";
cin >> quiz[ctr];
sum = sum + quiz[ctr];
}
ave = sum / 5;
cout << "Your average quiz from ";
for(ctr=0;ctr<5;ctr++)
{
cout << quiz[ctr] << ",";
}
return 0;
Problem #2:
Write a program that will accept 5 input numbers and then it will display all your original inputs and separate
even numbers from odd numbers as shown below.
Sample I/O:
Enter a number: 5
Enter a number: 20
Enter a number: 7
Enter a number: 200
Enter a number: 670
Code:
#include <iostream>
using namespace std;
int main()
{
int ctr, num[5];
Page 9 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
for(ctr=0;ctr<5;ctr++)
{
cout << "Enter a number: ";
cin >> num[ctr];
}
for(ctr=0;ctr<5;ctr++)
{
cout << num[ctr] << " ";
}
for(ctr=0;ctr<5;ctr++)
{
if(num[ctr]%2==0)
cout << num[ctr] << " ";
}
for(ctr=0;ctr<5;ctr++)
{
if(num[ctr]%2==1)
cout << num[ctr] << " ";
}
return 0;
}
int main()
int num[5];
int location[5];
int ctr, x, count=0;
for(ctr=0;ctr<5;ctr++)
{
Page 10 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
}
cout<<"-------------------------------\n";
for(ctr=0;ctr<5;ctr++)
{
if(num[ctr] == x)
{
count++;
location[ctr] = num[ctr];
}
}
for(ctr=0;ctr<5;ctr++)
{
if(location[ctr] == x)
{
cout<<ctr <<",";
}
}
cout<<"\n\n";
}
}
Output of example # 2:
Number:12
Number:12
Number:2
Number:12
Number:3
-------------------------------
Enter a value to search: 12
Occurrence = 3
Located at index = 0,1,3,
Using cin you cannot take input the entire string have words in between them.
syntax:
getline(cin,str)
Page 11 of 13
Lesson 1: Array CC123 ( C ) – Intermediate Programming (Advanced C++)
compare()
compare() returns an integer, which is a measure of the difference between the two strings.
A return value of 0 indicates that the two strings compare as equal.
Returns:
0 : if both strings are equal.
A value < 0 : if *this is shorter than str or,
first character that doesn't match is smaller than str.
A value > 0 : if *this is longer than str or,
first character that doesn't match is greater
Problem #3:
Write a program that will accept 5 input string values and a word to be located from the said inputs. The
program will determine if there is match between the search word and the 5 string inputs. It will also
determine the location/indexes from which the search word appears.
Sample I/O:
if(occ==1)
{
cout << "\nMatch Found..\nLocated at indexes: ";
for(i=0; i<5; i++)
{
if(occ_index[i] != -1)
{
cout << i << " ";
}
}
}
else
{
cout << "\nMatch not found!";
}
return 0;
}
Prepared by:
Page 13 of 13