Chapter 2 - Arrays
Chapter 2 - Arrays
2.1. Introduction
Variables in a program have values associated with them. During program execution
these values are accessed by using the identifier associated with the variable in
expressions etc. In none of the programs written so far have very many variables been
used to represent the values that were required. Thus even though programs have been
written that could handle large lists of numbers it has not been necessary to use a separate
identifier for each number in the list. This is because in all these programs it has never
been necessary to keep a note of each number individually for later processing. For
example in summing the numbers in a list only one variable was used to hold the current
entered number which was added to the accumulated sum and was then overwritten by
the next number entered. If that value were required again later in the program there
would be no way of accessing it because the value has now been overwritten by the later
input.
If only a few values were involved a different identifier could be declared for each
variable, but now a loop could not be used to enter the values. Using a loop and assuming
that after a value has been entered and used no further use will be made of it allows the
following code to be written. This code enters six numbers and outputs their sum:
sum = 0.0;
for (i = 0; i < 6; i++)
{
cin >> x;
sum += x;
}
This of course is easily extended to n values where n can be as large as required.
However if it was required to access the values later the above would not be suitable. It
would be possible to do it as follows by setting up six individual variables:
float a, b, c, d, e, f;
which is obviously a very tedious way to program. To extend this solution so that it
would work with more than six values then more declarations would have to be added,
extra assignment statements added and the program re-compiled. If there were 10000
values imagine the tedium of typing the program (and making up variable names and
remembering which is which)!
To get round this difficulty all high-level programming languages use the concept of a
data structure called an Array.
An array can be thought of as a collection of numbered boxes each containing one data
item. The number associated with the box is the index of the item. To access a particular
item the index of the box associated with the item is used to access the appropriate box.
The index must be an integer and indicates the position of the element in the array. Thus
the elements of an array are ordered by the index.
For example data on the average temperature over the year in Ethiopia for each of the last
100 years could be stored in an array declared as follows:
float annual_temp[100];
This declaration will cause the compiler to allocate space for 100 consecutive float
variables in memory. The number of elements in an array must be fixed at compile time.
It is best to make the array size a constant and then, if required, the program can be
changed to handle a different size of array by changing the value of the constant,
then if more records come to light it is easy to amend the program to cope with more
values by changing the value of NE. This works because the compiler knows the value of
the constant NE at compile time and can allocate an appropriate amount of space for the
array. It would not work if an ordinary variable was used for the size in the array
declaration since at compile time the compiler would not know a value for it.
An array element is accessed by writing the identifier of the array followed by the
subscript in square brackets. Thus to set the 15th element of the array above to 1.5 the
following assignment is used:
annual_temp[14] = 1.5;
Note that since the first element is at index 0, then the ith element is at index i-1. Hence
in the above the 15th element has index 14.
An array element can be used anywhere an identifier may be used. Here are some
examples assuming the following declarations:
count[i] += 5;
Array elements can form part of the condition for an if statement, or indeed, for any other
logical expression:
The following code finds the average temperature recorded in the first ten elements of the
array.
sum = 0.0;
for (i = 0; i <10; i++)
sum += annual_temp[i];
av1 = sum / 10;
Notice that it is good practice to use named constants, rather than literal numbers such as
10. If the program is changed to take the average of the first 20 entries, then it all too easy
to forget to change a 10 to 20. If a const is used consistently, then changing its value will
be all that is necessary.
For example, the following example finds the average of the last k entries in the array. k
could either be a variable, or a declared constant. Observe that a change in the value of k
will still calculate the correct average (provided k<=NE).
sum = 0.0;
for (i = NE - k; i < NE; i++)
sum += annual_temp[i];
av2 = sum / k;
Important - C++ does not check that the subscript that is used to reference an array
element actually lies in the subscript range of the array. Thus C++ will allow the
assignment of a value to annual_temp[200], however the effect of this assignment is
unpredictable. For example it could lead to the program attempting to assign a value to a
memory element that is outside the program's allocated memory space. This would lead
to the program being terminated by the operating system. Alternatively it might actually
access a memory location that is within the allocated memory space of the program and
assign a value to that location, changing the value of the variable in your program which
is actually associated with that memory location, or overwriting the machine code of your
program. Similarly reading a value from annual_temp[200] might access a value that
has not been set by the program or might be the value of another variable. It is the
programmer's responsibility to ensure that if an array is declared with n elements then no
attempt is made to reference any element with a subscript outside the range 0 to n-1.
Using an index, or subscript, that is out of range is called Subscript Overflow. Subscript
overflow is one of the commonest causes of erroneous results and can frequently cause
very strange and hard to spot errors in programs.
Note that the array has not been given a size, the compiler will make it large enough to
hold the number of elements in the list. In this case primes would be allocated space for
seven elements. If the array is given a size then this size must be greater than or equal to
the number of elements in the initialization list. For example:
A set of positive data values (200) are available. It is required to find the average value of
these values and to count the number of values that are more than 10% above the average
value.
Since the data values are all positive a negative value can be used as a sentinel to signal
the end of data entry. Obviously this is a problem in which an array must be used since
the values must first be entered to find the average and then each value must be compared
with this average. Hence the use of an array to store the entered values for later re-use.
In the above the variable nogt10 is the number greater than 10% above the average value.
It is easy to argue that after exiting the while loop, count is set to the number of positive
numbers entered. Before entering the loop count is set to zero and the first number is
entered, that is count is one less than the number of numbers entered. Each time round the
loop another number is entered and count is incremented hence count remains one less
than the number of numbers entered. But the number of numbers entered is one greater
than the number of positive numbers so count is therefore equal to the number of positive
numbers.
A main() program written from the above algorithmic description is given below:
void main()
{
const int NE = 200; // maximum no of elements in array
float sum = 0.0; // accumulates sum
int count = 0; // number of elements entered
int nogt10 = 0; // counts no greater than 10%
// above average
float x; // holds each no as input
float indata[NE]; // array to hold input
float average; // average value of input values
int i; // control variable
// calculate average
average = sum/count;
// Output results
cout << "Number of values input is " << n;
cout << endl
<< "Number more than 10% above average is "
<< nogt10 << endl;
}
Since it was assumed in the specification that there would be less than 200 values the
array size is set at 200. In running the program less than 200 elements may be entered, if
n elements where n < 200 elements are entered then they will occupy the first n places in
the array indata. It is common to set an array size to a value that is the maximum we
think will occur in practice, though often not all this space will be used.
The following program simulates the throwing of a dice by using a random number
generator to generate integers in the range 0 to 5. The user is asked to enter the number of
trials and the program outputs how many times each possible number occurred.
An array has been used to hold the six counts. This allows the program to increment the
correct count using one statement inside the loop rather than using a switch statement
with six cases to choose between variables if separate variables had been used for each
count. Also it is easy to change the number of sides on the dice by changing a constant.
Because C++ arrays start at subscript 0 the count for an i occurring on a throw is held in
the i-1th element of this count array. By changing the value of the constant die_sides the
program could be used to simulate a die_sides-sided die without any further change.
#include <iostream.h>
#include <stdlib.h> // time.h and stdlib.h required for
#include <time.h> // random number generation
void main()
{
const int die_sides = 6; // maxr-sided die
int count[die_sides]; // holds count of each
// possible value
int no_trials, // number of trials
roll, // random integer
i; // control variable
float sample; // random fraction 0 .. 1
Notice the use of a constant to store the array size. This avoids the literal constant '10'
appearing a number times in the code. If the code needs to be edited to use different sized
arrays, only the constant needs to be changed. If the constant is not used, all the '10's
would have to be changed individually - it is easy to miss one out.
Arrays can have any number of dimensions, although most of the arrays that you create
will likely be of one or two dimensions.
Suppose the program contains a class named square. The declaration of array named
board that represents would be
Square board[8][8];
The program could also represent the same data with a one dimensional, 64-square array.
For example, it could include the statement
Square board[64];
Such a representation does not correspond as closely to the real-world object as the two
dimensional array, however.
Suppose that when the game begins. The king id located in the fourth position in the first
row. Counting from zero that position corresponds to board[0][3] in the two dimensional
array, assuming that the first subscript corresponds to the row, and the second to the
column.
int x[] = { 1, 2, 3, 4} ;
This initialization creates an array of four elements.
Note however:
int x[][] = { {1,2}, {3,4} } ; // error is not allowed.
and must be written
int x[2][2] = { {1,2}, {3,4} } ;
Example of multidimensional array
#include<iostream.h>
void main(){
int SomeArray[5][2] = {{0,0},{1,2}, {2,4},{3,6},
{4,8}}
for ( int i=0; i<5; i++)
for (int j = 0; j<2;j++)
{
cout<<"SomeArray["<<i<<"]["<<j<<'']: '';
cout<<endl<<SomeArray[i][ j];
}
}
In C++ strings of characters are held as an array of characters, one character held in
each array element. In addition a special null character, represented by `\0', is appended
to the end of the string to indicate the end of the string. Hence if a string has n characters
then it requires an n+1 element array (at least) to store it. Thus the character `a' is stored
in a single byte, whereas the single-character string "a" is stored in two consecutive bytes
holding the character `a' and the null character.
The string variable s1 could hold strings of length up to nine characters since space is
needed for the final null character. Strings can be initialized at the time of declaration just
as other variables are initialized. For example:
In the first case the array would be allocated space for eight characters, that is space for
the seven characters of the string and the null character. In the second case the string is
set by the declaration to be twenty characters long but only sixteen of these characters are
set, i.e. the fifteen characters of the string and the null character. Note that the length of a
string does not include the terminating null character.
Note that the last two elements are a relic of the initialization at declaration time. If the
string that is entered is longer than the space available for it in the character array then
C++ will just write over whatever space comes next in memory. This can cause some
very strange errors when some of your other variables reside in that space!
We have solved the problem of reading strings with embedded blanks, but what about
strings with multiple lines? It turns out that the cin::get() function can take a third
argument to help out in this situation.
This argument specifies the character that tells the function to stop reading. The default
value of this argument is the newline('\n')character, but if you call the function
with some other character for this argument, the default will be overridden by the
specified character.
In the next example, we call the function with a dollar sign ('$') as the third argument
//reads multiple lines, terminates on '$' character
#include<iostream.h>
void main(){
const int max=80;
char str[max];
cout<<"\n Enter a string:\n";
[Link](str, max, '$'); //terminates with $
cout<<\n You entered:\n"<<str; }
now you can type as many lines of input as you want. The function will continue to
accept characters until you enter the terminated character $ (or untill you exceed the size
of the array. Remember, you must still press Enter key after typing the '$' character .
However, it is possible to tell the >> operator to limit the number of characters it places
in an array.
#include<iostream.h>
void main(){
char str[] = "Welcome to C++ programming language";
cout<<str;
}
if you tried to the string program with strings that contain more than one word , you may
have unpleasant surprise. Copying string the hard way
The best way to understand the true nature of strings is to deal with them character by
character
#include<iostream.h>
#include<string.h> //for strlen()
void main()
{
const int max=80;
char str1[]='' Oh, Captain, my Captain!"
our fearful trip is done";
char str2[max];
for(int i=0; i<strlen(str1);i++)
str2[i]=str1[1];
str2[i]='\0';
cout<<endl;
cout<<str2;
}
strcpy(destination, source);
strcpy copies characters from the location specified by source to the location
specified by destination. It stops copying characters after it copies the terminating null
character.
Example:
#include <iostream.h>
#include <string.h>
void main(){
char me[20] = "David";
cout << me << endl;
strcpy(me, "YouAreNotMe");
cout << me << endl ;
return;
}
There is also another function strncpy, is like strcpy, except that it copies only a
specified number of characters.
strncpy(destination, source, int n);
strcat(destination, source);
o The first character of the source string is copied to the location of the terminating null
character of the destination string.
o The destination string must have enough space to hold both strings and a terminating
null character.
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strcat(str1, "def");
cout << str1 << endl;
The function strncat is like strcat except that it copies only a specified number of
characters.
strncat(destination, source, int n);
It may not copy the terminating null character.
Example:
#include <iostream.h>
#include <string.h>
void main() {
char str1[30];
strcpy(str1, "abc");
cout << str1 << endl;
strncat(str1, "def", 2);
str1[5] = '\0';
cout << str1 << endl;
char str2[] = "xyz";
strcat(str1, str2);
cout << str1 << endl;
str1[4] = '\0';
cout << str1 << endl;
}
strncmp does not compare characters after a terminating null character has been found
in one of the strings.
Example:
#include <iostream.h>
#include <string.h>
void main()
{
cout << strncmp("abc", "def", 2) << endl;
cout << strncmp("abc", "abcdef", 3) << endl;
cout << strncmp("abc", "abcdef", 2) << endl;
cout << strncmp("abc", "abcdef", 5) << endl;
cout << strncmp("abc", "abcdef", 20) << endl;
}
2.6. Pointer
A pointer is the memory address of a variable. However, even though a pointer is a
memory address and a memory address is a number, you cannot store a pointer in a
variable of type int or double . A variable to hold a pointer must be declared to have a
pointer type. For example, the following declares p to be a pointer variable that can hold
one pointer that points to a variable of type double : double *p; The variable p can hold
pointers to variables of type double , but it cannot normally contain a pointer to a variable
of some other type, such as int or char . Each variable type requires a different pointer
type. For example, the following declares the variables p1 and p2 so they can hold
pointers to variables of type int ; it also declares two ordinary variables v1 and v2 of type
int: int *p1, *p2, v1, v2; There must be an asterisk before each of the pointer variables. If
you omit the second asterisk in the above declaration, then p2 will not be a pointer
variable; it will instead be an ordinary variable of type int .
The address that locates a variable within memory is what we call a reference to that
variable. This reference to a variable can be obtained by preceding the identifier of a
variable with an ampersand sign (&), known as reference operator, and which can be
literally translated as "address of". For example:
ted = &andy;
This would assign to ted the address of variable andy, since when preceding the name of
the variable andy with the reference operator (&) we are no longer talking about the
content of the variable itself, but about its reference (i.e., its address in memory).
From now on we are going to assume that andy is placed during runtime in the memory
address 1776. This number (1776) is just an arbitrary assumption we are inventing right
now in order to help clarify some concepts in this tutorial, but in reality, we cannot know
before runtime the real value the address of a variable will have in memory.
Consider the following code fragment:
1 andy = 25;
2 fred = andy;
3 ted = &andy;
The values contained in each variable after the execution of this, are shown in the
following diagram:
First, we have assigned the value 25 to andy (a variable whose address in memory we
have assumed to be 1776).
The second statement copied to fred the content of variable andy (which is 25). This is a
standard assignment operation, as we have done so many times before.
Finally, the third statement copies to ted not the value contained in andy but a reference
to it (i.e., its address, which we have assumed to be 1776). The reason is that in this third
assignment operation we have preceded the identifier andy with the reference operator
(&), so we were no longer referring to the value of andy but to its reference (its address
in memory).
The variable that stores the reference to another variable (like ted in the previous
example) is what we call a pointer. Pointers are a very powerful feature of the C++
language that has many uses in advanced programming. Farther ahead, we will see how
this type of variable is used and declared.
Using a pointer we can directly access the value stored in the variable which it points to.
To do this, we simply have to precede the pointer's identifier with an asterisk (*), which
acts as dereference operator and that can be literally translated to "value pointed by".
Therefore, following with the values of the previous example, if we write:
beth = *ted;
(that we could read as: "beth equal to value pointed by ted") beth would take the value
25, since ted is 1776, and the value pointed by 1776 is 25.
You must clearly differentiate that the expression ted refers to the value 1776, while *ted
(with an asterisk * preceding the identifier) refers to the value stored at address 1776,
which in this case is 25. Notice the difference of including or not including the
dereference operator (I have included an explanatory commentary of how each of these
two expressions could be read):
Thus, they have complementary (or opposite) meanings. A variable referenced with &
can be dereferenced with *.
Earlier we performed the following two assignment operations:
1 andy = 25;
2 ted = &andy;
Right after these two statements, all of the following expressions would give true as
result:
1 andy == 25
2 &andy == 1776
3 ted == 1776
4 *ted == 25
The first expression is quite clear considering that the assignment operation performed on
andy was andy=25. The second one uses the reference operator (&), which returns the
address of variable andy, which we assumed it to have a value of 1776. The third one is
somewhat obvious since the second expression was true and the assignment operation
performed on ted was ted=&andy. The fourth expression uses the dereference operator
(*) that, as we have just seen, can be read as "value pointed by", and the value pointed by
ted is indeed 25.
So, after all that, you may also infer (conclude) that for as long as the address pointed by
ted remains unchanged the following expression will also be true:
*ted == andy
Declaring variables of pointer types:
I want to emphasize that the asterisk sign (*) that we use when declaring a pointer only
means that it is a pointer (it is part of its type compound specifier), and should not be
confused with the dereference operator that we have seen a bit earlier, but which is also
written with an asterisk (*). They are simply two different things represented with the
same sign.
First, we have assigned as value of mypointer a reference to firstvalue using the reference
operator (&). And then we have assigned the value 10 to the memory location pointed by
mypointer, that because at this moment is pointing to the memory location of firstvalue,
this in fact modifies the value of firstvalue.
In order to demonstrate that a pointer may take several different values during the same
program I have repeated the process with secondvalue and that same pointer, mypointer.
Here is an example a little bit more elaborated:
Notice that there are expressions with pointers p1 and p2, both with and without
dereference operator (*). The meaning of an expression using the dereference operator
(*) is very different from one that does not: When this operator precedes the pointer
name, the expression refers to the value being pointed, while when a pointer name
appears without this operator, it refers to the value of the pointer itself (i.e. the address of
what the pointer is pointing to).
Another thing that may call your attention is the line:
This declares the two pointers used in the previous example. But notice that there is an
asterisk (*) for each pointer, in order for both to have type int* (pointer to int).
Otherwise, the type for the second variable declared in that line would have been int (and
not int*) because of precedence relationships. If we had written:
p1 would indeed have int* type, but p2 would have type int (spaces do not matter at all
for this purpose). This is due to operator precedence rules. But anyway, simply
remembering that you have to put one asterisk per pointer is enough for most pointer
users.
The concept of array is very much bound to the one of pointer. In fact, the identifier of an
array is equivalent to the address of its first element, as a pointer is equivalent to the
address of the first element that it points to, so in fact they are the same concept. For
example, supposing these two declarations:
p = numbers;
After that, p and numbers would be equivalent and would have the same properties. The
only difference is that we could change the value of pointer p by another one, whereas
numbers will always point to the first of the 20 elements of type int with which it was
defined. Therefore, unlike p, which is an ordinary pointer, numbers is an array, and an
array can be considered a constant pointer. Therefore, the following allocation would not
be valid:
numbers = p;
In the chapter about arrays we used brackets ([]) several times in order to specify the
index of an element of the array to which we wanted to refer. Well, these bracket sign
operators [] are also a dereference operator known as offset operator. They dereference
the variable they follow just as * does, but they also add the number between brackets to
the address being dereferenced. For example:
1 a[5] = 0; // a [offset of 5] = 0
2 *(a+5) = 0; // pointed by (a+5) = 0
These two expressions are equivalent and valid both if a is a pointer or if a is an array.
Pointer initialization
When declaring pointers we may want to explicitly specify which variable we want them
to point to:
1 int number;
2 int *tommy = &number;
1 int number;
2 int *tommy;
3 tommy = &number;
When a pointer initialization takes place we are always assigning the reference value to
where the pointer points (tommy), never the value being pointed (*tommy). You must
consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is
a pointer, it is not the dereference operator (although both use the same sign: *).
Remember, they are two different functions of one sign. Thus, we must take care not to
confuse the previous code with:
1 int number;
2 int *tommy;
3 *tommy = &number;
that is incorrect, and anyway would not have much sense in this case if you think about it.
As in the case of arrays, the compiler allows the special case that we want to initialize the
content at which the pointer points with constants at the same moment the pointer is
declared:
It is important to indicate that terry contains the value 1702, and not 'h' nor "hello",
although 1702 indeed is the address of both of these.
The pointer terry points to a sequence of characters and can be read as if it was an array
(remember that an array is just like a constant pointer). For example, we can access the
fifth element of the array with any of these two expression:
1 *(terry+4)
2 terry[4]
Both expressions have a value of 'o' (the fifth element of the array).
C++ allows the use of pointers that point to pointers, that these, in its turn, point to data
(or even to other pointers). In order to do that, we only need to add an asterisk (*) for
each level of reference in their declarations:
1 char a;
2 char * b;
3 char ** c;
4 a = 'z';
5 b = &a;
6 c = &b;
This, supposing the randomly chosen memory locations for each variable of 7230, 8092
and 10502, could be represented as:
The value of each variable is written inside each cell; under the cells are their respective
addresses in memory.
The new thing in this example is variable c, which can be used in three different levels of
indirection, each one of them would correspond to a different value: