CC103 Mod4
CC103 Mod4
0 10-July-2020
ARRAYS
MODULE OVERVIEW
The previous modules discussed how grouping related statements into one name through function declaration
and definition makes it easy for programmers to break down a large problem into manageable tasks. The
concept of grouping can also be applied to variables. All of the variables we have used so far are simple
variables that are unrelated to any other variable in memory. However, some programs will require the use of
variables that are related to each other to make it easier and more efficient to treat the related variables as a
group. To do this, we group together related variables that have the same data type, which is referred to as an
array of variables or, more simply, an array. You will learn in this module how the variables in an array can be
used just like any other variables. You can assign values to them, use them in calculations, display their
contents, and so on.
Introduction
An array is a collection of variables of the same type that are referred to by a common name. Arrays may
have from one to several dimensions, although the one-dimensional array is the most common. Arrays offer a
convenient means of creating lists of related variables. The array that you will probably use most often is the
character array, because it is used to hold a character string. The C++ language does not define a built-in
string data type. Instead, strings are implemented as arrays of characters. This approach to strings allows
greater power and flexibility than are available in languages that use a distinct string type.
4. Array
An array is a series of elements of the same type placed in contiguous memory locations that can be
individually referenced by adding an index to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having to declare 5
different variables, each one with a different identifier. Instead of that, using an array we can store 5 different
values of the same type, int for example, with a unique identifier.
For example, an array to contain 5 integer values of type int called my_array could be represented like
this:
where each blank panel represents an element of the array, that in this case are integer values of type int.
These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its
length.
Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++
is:
where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always
enclosed in square brackets []), specifies how many of these elements the array has to contain.
Therefore, in order to declare an array called my_array as the one shown in the above diagram it is as
simple as:
int my_array[5];
NOTE: The elements field within brackets [] which represents the number of elements the array is going to
hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be
determined before execution. In order to create arrays with a variable length dynamic memory is needed.
In both cases, local and global, when we declare an array, we have the possibility to assign initial values to
each one of its elements by enclosing the values in braces { }. For example:
The amount of values between braces { } must not be larger than the number of elements that we declare for
the array between square brackets [ ]. For example, in the example of array my_array we have declared that
it has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each
element.
When an initialization of values is provided for an array, C++ allows the possibility of leaving the square
brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of
values included between braces { }:
After this declaration, array my_array would be 5 integers long, since we have provided 5 initialization
values.
name[index]
Following the previous examples in which my_array had 5 elements and each of those elements was of
type int, the name which we can use to refer to each element is the following:
For example, to store the value 75 in the third element of my_array, we could write the following statement:
my_array[2] = 75;
and, for example, to pass the value of the third element of my_array to a variable called a, we could write:
a = my_array[2];
Therefore, the expression my_array[2]is for all purposes like a variable of type int.
Notice that the third element of my_array is specified my_array[2], since the first one is my_array[0],
the second one is my_array[1], and therefore, the third one is my_array[2]. By this same reason, its last
element is my_array[4]. Therefore, if we write my_array[5], we would be accessing the sixth element
of my_array and therefore exceeding the size of the array.
In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems,
since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The
reason why this is allowed will be seen further ahead when we begin to use pointers.
At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related
to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and
the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of
brackets [ ] with arrays.
If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it
never precedes an access.
int my_array[]= {1, 45, 89, 5, 87, 23, 100, 4, 5, 33, 23 45, 90};
my_array[0]= a;
my_array[a] =75;
b= my_array[a+2];
my_array[8] =5;
my_array[my_array[a]] = my_array[2] + 5;
To see how the valid operations work, let us take a look at the code below:
#include <iostream>
using namespace std;
int main()
{
int a=8;
int b;
int my_array[]= {1, 45, 89, 5, 87, 23, 100, 4, 5, 33, 23, 45, 90};
cout<<"Initial array elements: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}
my_array[0]= a;
my_array[a] =75;
cout<<"\n The value of index 8 is "<<my_array[a];
b= my_array[a+2];
cout<<"\n The value of variable b is: "<<b;
my_array[8] =5;
cout<<"\n after assignments of values: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}
my_array[my_array[a]] = my_array[2] + 5;
cout<<"\n The value of index 5 is: "<<my_array[5];
cout<<"\n After the code in line 32 was executed: ";
for (int i=0; i<13; i++) {
cout<<my_array[i] <<",";
}
b=my_array[13];
cout<<b;
return 0;
}
is an array that can store up to 20 elements of type char. It can be represented as:
Therefore, in this array, in theory, we can store sequences of characters up to 20 characters long. But we can
also store shorter sequences. For example, jenny could store at some point in a program either the
sequence "Hello" or the sequence "Merry Christmas", since both are shorter than 20 characters.
Therefore, since the array of characters can store shorter sequences than its total length, a special character
is used to signal the end of the valid sequence: the null character, whose literal constant can be written as '\
0'(backslash, zero).
Our array of 20 elements of type char, called jenny, can be represented storing the characters
sequences "Hello" and "Merry Christmas" as:
Notice how after the valid content a null character ('\0') has been included in order to indicate the end of the
sequence. The panels in gray color represent char elements with undetermined values.
In this case we would have declared an array of 6 elements of type char initialized with the characters that
form the word "Hello" plus a null character '\0' at the end.
But arrays of char elements have an additional method to initialize their values: using string literals.
In the expressions we have used in some examples, constants that represent entire strings of characters have
already showed up several times. These are specified enclosing the text to become a string literal between
double quotes ("). For example:
Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters. So
string literals enclosed between double quotes always have a null character ('\0') automatically appended at
the end.
Therefore we can initialize the array of char elements called myword with a null-terminated sequence of
characters by either one of these two methods:
Notice that we are talking about initializing an array of characters in the moment it is being declared, and not
about assigning values to them once they have already been declared. In fact because this type of null-
terminated arrays of characters are regular arrays we have the same restrictions that we have with any other
array, so we are not able to copy blocks of data with an assignment operation.
1 mystext = "Hello";
2 mystext[] = "Hello";
The reason for this may become more comprehensible once you know a bit more about pointers, since then it
will be clarified that an array is in fact a constant pointer pointing to a block of memory.
As you can see, we have declared three arrays of char elements. The first two were initialized with string
literal constants, while the third one was left uninitialized. In any case, we have to specify the size of the array:
in the first two (question and greeting) the size was implicitly defined by the length of the literal constant they
were initialized to. While for yourname we have explicitly specified that it has a size of 80 chars.
Finally, sequences of characters stored in char arrays can easily be converted into string objects just by using
the assignment operator:
1 string mystring;
2 char myntcs[]="some text";
3 mystring = myntcs;
Although this program is technically correct, it will not always work the way that you expect. To see why, run
the program and try entering the string “This is a test”. Here is what you will see:
Enter a string: This is a test
Here is your string: This
When the program redisplays your string, it shows only the word “This”, not the entire sentence. The reason
for this is that the C++ I/O system stops reading a string when the first whitespace character is encountered.
Whitespace characters include spaces, tabs, and newlines.
One way to solve the whitespace problem is to use another of C++’s library functions, gets(). The general form
of a call to gets() is
gets(array-name);
To read a string, call gets() with the name of the array, without any index, as its argument. Upon return from
gets(), the array will hold the string input from the keyboard. The gets() function will continue to read
characters, including whitespace, until you enter a carriage return. The header used by gets() is <cstdio>.
This version of the preceding program uses gets() to allow the entry of strings containing spaces:
Now, spaces are read and included in the string. One other point: Notice that in a cout statement, str can be
used directly. In general, the name of the character array that holds a string can be used any place that a
string constant can be used.
Keep in mind that neither cin nor gets() performs any bounds checking on the array that receives input.
Therefore, if the user enters a string longer than the size of the array, the array will be overwritten.
type name[size1][size2]...[sizeN];
int multidim[4][10][3];
Arrays of more than three dimensions are not often used, due to the amount of memory required to
hold them. Remember, storage for all array elements is allocated during the entire lifetime of an array. When
multidimensional arrays are used, large amounts of memory can be consumed. For example, a four-
dimensional character array with dimensions 10,6,9,4 would require 10×6×9×4 (or 2,160) bytes. If each array
dimension is increased by a factor of 10 each (that is, 100×60×90×40), then the memory required for the array
increases to 21,600,000 bytes! As you can see, large multidimensional arrays may cause a shortage of
memory for other parts of your program. Thus, a program with arrays of more than two or three dimensions
may find itself quickly out of memory!
Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be
imagined as a bidimensional table made of elements, all of them of a same uniform data type.
jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++
would be:
float my_array[63][14];
and, for example, the way to reference the second element vertically and fourth horizontally in an expression
would be:
jimmy[1][3]
Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many
indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each
dimension. For example:
declares an array with a char element for each second in a century, that is more than 3 billion chars. So this
declaration would consume more than 3 gigabytes of memory!
Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a
simple array just by putting a factor between its indices:
With the only difference that with multidimensional arrays the compiler remembers the depth of each
imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result.
One uses a bidimensional array and the other one uses a simple array:
None of the two source codes above produce any output on the screen, but both assign values to the memory
block called jimmy in the following way:
We have used "defined constants" (#define) to simplify possible future modifications of the program. For
example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by
changing the line:
#define HEIGHT 3
to:
#define HEIGHT 4
The above method is not preferred. A better way to initialize this array with the same array elements is given
below:
int test[2][3] = { {2, 4, 5}, {9, 0, 19}};
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.
This is not a good way of initializing a three-dimensional array. A better way to initialize this array is:
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
Notice the dimensions of this three-dimensional array. The first dimension has the value 2. So, the two
elements comprising the first dimension are:
Element 1 = { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }
Element 2 = { {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
The second dimension has the value 3. Notice that each of the elements of the first dimension has three
elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
{13, 4, 56, 3}, {5, 9, 3, 5} and {5, 1, 4, 9} for Element 2.
Finally, there are four int numbers inside each of the elements of the second dimension:
{3, 4, 2, 3}
{0, -3, 9, 11}
... .. ...
... .. ...
#include <iostream>
using namespace std;
int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};
return 0;
}
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
In the above example, we have initialized a two-dimensional int array named test that has 3 "rows" and 2
"columns".
Here, we have used the nested for loop to display the array elements.
the outer loop from i == 0 to i == 2 access the rows of the array
the inner loop from j == 0 to j == 1 access the columns of the array
int main() {
int numbers[2][3];
return 0;
}
Output
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
Here, we have used a nested for loop to take the input of the 2d array. Once all the input has been taken, we
have used another nested for loop to print the array members.
#include <iostream>
int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2}, [0] [0][0], [0][0][1]
{3, 4}, [0] [1][0], [0] [1][1]
{5, 6} [0] [2][0], [0] [2][1]
},
{
{7, 8}, [1] [0][0], [1][0][1]
{9, 10}, [1][1][0], [1][1][1]
{11, 12} [1][2][0], [1][2][1]
}
};
return 0;
}
Output
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
As we can see, the complexity of the array increases exponentially with the increase in dimensions.
In order to accept arrays as parameters the only thing that we have to do when declaring the function is to
specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For
example, the following function:
accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:
procedure (myarray);
1 // arrays as parameters 5 10 15
2 #include <iostream> 2 4 6 8 10
3 using namespace std;
4
5 void printarray (int arg[], int length) {
6 for (int n=0; n<length; n++)
7 cout << arg[n] << " ";
8 cout << "\n";
9}
10
11 int main ()
12 {
13 int firstarray[] = {5, 10, 15};
14 int secondarray[] = {2, 4, 6, 8, 10};
15 printarray (firstarray,3);
16 printarray (secondarray,5);
17 return 0;
18 }
The first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that
reason we have included a second parameter that tells the function the length of each array that we pass to it
as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the
passed array without going out of range.
In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional
array parameter is:
base_type[][depth][depth]
Notice that the first brackets [] are left empty while the following ones specify sizes for their respective
dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional
dimension.
Output:
Displaying Values:
num[0][0]: 3
num[0][1]: 4
num[1][0]: 9
num[1][1]: 5
num[2][0]: 7
num[2][1]: 1
In the above program, we have defined a function named display(). The function takes a two dimensional
array, int n[][2] as its argument and prints the elements of the array.
While calling the function, we only pass the name of the two dimensional array as the function
argument display(num).
Note: It is not mandatory to specify the number of rows in the array. However, the number of columns should
always be specified. This is why we have used int n[][2].
We can also pass arrays with more than 2 dimensions as a function argument.
Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors
for novice programmers.
LEARNING ACTIVITY 3
b. A two-dimensional array representing the days on a calendar page that may contain a
maximum of 6 weeks. Call the array weeks, and declare an enumeration type consisting of
the names of the days, which can be used to index the array columns. The weeks should be
indexed by an int.
c. Write a declaration of a named array type, and then declare three arrays of that type. The
array type should be called DataSet, and the three arrays should be called input, output, and
working. Each array should hold five float values.
4. Each dimension in a multidimensional array is specified with its own set of brackets. True or False?
5. Show how to declare a two-dimensional integer array called list with the dimensions 4x9.
6. Given list from the preceding question, show how to access element 2,3.
7. What is a null-terminated string?
8. To hold a string that is 8 characters long, how long must the character array be?
9. What function can be used to read a string containing spaces from the keyboard?
Case Study:
1. A piano is tuned in a scale that is slightly unequal (called a “well-tempered scale”), rather than a
perfectly scientific scale in which each note sounds at twice the frequency of the same note an octave
below (called a “just scale”). For this reason, we can’t simply calculate the frequency of a note, but
rather must keep it in a table. Declare a two-dimensional array (scale) to hold the frequencies of the
well-tempered scale. Afrequency is represented by a float value.
2. Write a program to play a game in which you try to sink a fleet of five navy vessels by guessing their
locations on a grid. The program uses random numbers to position its ships on a 15 x 15 grid. The
ships are of different lengths as follows:
Frigate: 2 locations
Tender: 2 locations
Destroyer: 3 locations
Cruiser: 3 locations
Carrier: 4 locations
The program must pick one square as the starting location, then pick the direction of the ship on the
board, and mark off the number of squares in that direction to represent the size of the ship. It must
not allow a ship to overlap with another ship, or to run off the board. The user enters coordinates in
the range of 1 through 15 for the rows and A through O for the columns. The program checks this
location, and reports whether the guess is a hit or a miss. If it is a hit, the program also checks
whether the ship has been hit in every location that it occupies. If so, the ship is reported as sunk, and
the program will terminate.
SUMMARY
Programmers use arrays to temporarily store related data in the computer’s internal memory. Using an array,
a programmer can increase the efficiency of a program since the data can be stored and retrieved much
faster. Further, the program can use the data stored in an array as many time as it is needed after it has been
entered. Each of the array elements that are stored in a one-dimensional array is assigned a unique index
number wherein the first element is assigned the index 0 and the last index is always assigned as one number
less than the number of elements. To access the elements in a one-dimensional array, we specify the array’s
name and the element’s index inside a square bracket. A two-dimensional array resembles a table in that the
elements are in rows and columns. You can determine the number of elements in a two-dimensional array by
multiplying the number of its rows by the number of its columns. Contrary to one-dimensional arrays, two-
dimensional arrays are identified by a unique combination of two indices. The first index represents the
element’s row location in an array, and the second index represents it column location. To refer to each
element in a two-dimensional array by the array’s name and the element’s indices, which are specified in two
sets of square brackets immediately following the name.
REFERENCES
[2] Dale, Nell; Weems, Chip; and Headington, Mark. (2001). Programming in C++, 2 nd Edition.
[3] Schildt, Herbert (2005). C++ A Beginner’s Guide Second Edition.Corel Ventura Publishers
https://www.programiz.com/cpp-programming/arrays
https://www.programiz.com/cpp-programming/multidimensional-arrays
https://www.programiz.com/cpp-programming/passing-arrays-function
https://www.programiz.com/cpp-programming/pointers-arrays
https://www.tutorialspoint.com/cplusplus/cpp_arrays.htm
https://www.cplusplus.com/doc/tutorial/arrays/
https://www.javatpoint.com/cpp-arrays
https://beginnersbook.com/2017/08/cpp-arrays/