%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
Arrays in c++
1. By: Asaye Chemeda Email: asayechemeda@yahoo.com 16
CHAPTER TWO
ARRAYS
Introduction
Throughout the first chapter, with the exception where
we used string data types few times, we mostly dealt with
simple data types such as integers, floating-point values
and characters. Those data types can store only a single
value. For the problems which we tried to solve in that
chapter, those data types were adequate. Because we
mostly dealt with variables which can be fully expressed
by a single value.
However, in real world problems, we may be interested in
some structured arrangement of those simple data types.
To give you a simple example, if you can structurally
arranged char data types, you will get a string. Those data
types which are formed by various structural arrangement
of the simple data types are termed as structured data
types. The simple data types are the building blocks of
the structured data types.
Structured data types which are formed from the same
(homogeneous) simple data type are known as arrays.
The data type an array is the same as the data type of the
building components or elements. For instance, a char
array has all its elements made from char data type. An
int array is made from all integer data types. The same is
true for other simple data types as well.
Before looking into the details of arrays, we will see the
scenarios where arrays become useful. For this, we will
start from simple programs.
First, let us write a program which takes five integers and
which prints their values as they are entered. Very easy. If
you remember for-loop, you can only define one int
variable.
Program 2.1[Correct].cpp
In the above program, the variable x takes five integer
values and prints them as they are entered.
Let us now put restriction on the above program. We will
still print all the values entered but we want to print them
in reverse order – from the value entered last to the value
entered first. Can we handle this restriction with only one
simple data type variable? Definitely not. We need to store
all the five values first to print them in reverse order. A
simple data type value can be accessed by using different
variables (such as reference variables) but it can only store
one value at a time. Therefore, only one simple data type
variable is not adequate to print what we wanted. Is there
another option? Simply, we can define five variables, we
store the five integers in them and print their values in
reverse order. In that case, we will have the following
program.
Program 2.2[Correct].cpp
In the above program, we worked only with five integer
values. Defining five variables was not that difficult. Now
consider yourself having such kind of problem involving
hundreds or thousands of values? Will you keep on
defining the same number of variables as the number of
values which you want to deal with? If that is the only
option we have, you will say C++ is not that decent, right?
For such problems, however, C++ has provided us with
the option to define only one array variable to store and
manipulate a number of simple data types of the same
kind. In the above program, all the data types of the
variables are of int data type. As a result, a single array can
be defined and can be used to store all the five integers.
No more defining on variable for every value.
Not only does C++ allow us to store and manipulate
those values via one array variable, it also provides us with
variety of options to arrange them. Those individual
simple data types in an array, can be arranged in various
number of dimensions. For instance, you can put them in
only one dimension. You can also put them in two
dimensions with specified numbers of rows and columns.
The option to arrange them in more than two dimensions
is also there. Those arrays which are formed by arranging
the simple data types in only one dimension are called
one-dimensional arrays. It is easy to guess what the other
arrays with more than one dimension would be called.
2. By: Asaye Chemeda Email: asayechemeda@yahoo.com 17
Deciding what array dimension to use is usually a straight
forward process. However, sometimes, it may become
tricky. To discuss how you may select the array
dimension, an array which will be defined to store a set of
all integers between 1 and 100 will be considered. You can
arrange these integers in different ways. You can put them
in 100 rows and 1 column or 50 rows and 2 columns or
in any other way where the product of the number of rows
and number of columns will be equal to the number of
elements. As far as the memory requirement is concerned,
the required memory size is the same for equal number of
the same data type elements whether the array is one-
dimensional, two-dimensional or multi-dimensional.
However, the lesser the array dimension, the lesser the
computational time required to access the array elements.
Therefore you need to be careful when you select array
dimensions where computation time is precious.
Usually, if each element in an array is not be associated
with another value that describes that particular element,
you use one-dimensional array. If you want to store
integers between 1 and 100, why would you use two-
dimensional array while each element is independent of
the other. Therefore in such cases, one-dimensional arrays
might be satisfactory. However, say, you want to store the
square of those integers as well along with the original
integers. In that case, each integer is associated with
another value – its square. In these case, two-dimensional
arrays become very handy and you will define a two-
dimensional array. The same reasoning goes for creating
multi-dimensional arrays.
When arrays are defined, it is mandatory to specify how
the array elements will be arranged. In other words, the
maximum number of elements that the array will have in
each dimension should be explicitly stated. The vertical
dimension is called a column while the horizontal
dimension is called a row. Therefore, when an array is
defined the number of rows and columns should be
explicitly stated.
The one-dimensional arrays are the simplest types of
arrays and we will start our discussion from them.
One-dimensional Arrays
In C++, one-dimensional arrays have one column but any
number of rows. These arrays are defined like other
simple data types. However, the number of rows that the
array will have should be specified during the array
definition. This is done by writing the array subscripting
operator, [ ], with the array size in the middle after the
identifier. A typical array definition is done as follows:
For instance, the following statement defines a one-
dimensional array named prime which can have up to 5
elements of int data type.
Like other simple data types, arrays can also be initialized.
The initialization can be partial or complete. To initialize
one-dimensional arrays, you will assign the array
definition with array element initializing values separated
by comas and bounded by braces. The following
statement initializes, the elements of the prime array
defined above with the first five prime numbers.
With this initialization, the first element of the prime
array will be initialized by a value of 2, the second by a
value of 3 and so on.
During initialization of one-dimensional arrays, the
number of values between the braces cannot be greater
than the prescribed size of the array but it can be less. If
the number of values within the braces is exactly equal to
the prescribed size of the array, the initialization is called
full initialization. However, you can also initialize the
array with fewer number of values than the prescribed
array size. This type of initialization is called partial
initialization. In that case, the array will be initialized by
those values starting from the first element. The following
statement partially initializes the prime array with two
elements. Only the first and the second element of the
array will be initialized.
With the above initialization, the first element of the
prime array will be initialized by a value of 2, the second
by a value of 3 and the rest elements will take default
values.
Arrays can also be initialized without explicitly stating the
size of the array. In that case, the compiler assumes the
array size is equal to the number of values between the
braces. Such type of array initialization is useful while
defining arrays with variable numbers of initialization
elements. Because it is not necessary to adjust the arrays
size every time the array is initialized with different
numbers of initializing values. For instance, the following
statement, which doesn’t explicitly state the array size, is
legal.
When the compiler encounters the above statement, it
will allocate a memory space for an array called prime
3. By: Asaye Chemeda Email: asayechemeda@yahoo.com 18
having array size of five and initializes the five elements
with the initializing values.
Is it getting boring? You might be saying this: we haven’t
written any program involving arrays but we discussed a
lot about them. You are right. Let us now create a
function which involves one-dimensional array.
Specifically, let us write a program which prints the
elements of the prime array which will be initialized with
the first five prime numbers.
Program 2.3[Doesnot print Array].cpp
In the above program, the prime array is defined and
initialized with on line 6. On line 7, we tried to print the
array elements. That is also what you are trying to print,
right? Run the program and see whether the numbers are
printed or not.
What did you get as an output? You got some strange
combination of numbers and characters, right? Look back
with what values you initialized the prime array and look
at the output. No relationship at all. Is the compiler wrong
this time? Not really. You will understand what the
compiler printed after few discussion regarding how
arrays are stored in the main memory.
When data items are defined in C++, the compiler will
allocate a memory space for the data items in the main
memory. Arrays, being structured data types, are data
items which the compiler will allocate memory for. The
main memory is comprised of ordered sequences of cells
each with memory size of one byte. Each cell has its own
unique location within the main memory called address of
the cell. Some data types may require more than one cell
in the main memory. For instance, an integer requires four
bytes and an integer variable occupies four cells in the
main memory.
As we discussed, arrays are structured data types
containing a number of similar simple data type values.
When arrays are defined, the compiler will allocate, a
contiguous (interconnected) memory locations for each
element of the array. The memory allocated for each
element varies according to the base type of the elements
of the array – one byte for char and bool, four bytes for
int and float and eight bytes for double.
An interesting fact to note here is that, the identifier used
for an array definition is associated with the memory
address of the first cell of the memory location where the
first element of the array is stored. The address of that
particular cell is known as the base address of the array.
Which means that, the identifiers used for an array definition
refer to the base address of the array.
Let us go back to our program and see what happened.
Have you got any clue why we obtained those strange
combinations of numbers and characters now?
Remember, prime is the identifier used for the array.
In line 7 of the program, hoping that the elements of the
array would be printed, we actually put the identifier of
the array in a cout statement. What we didn’t realize is
the identifier only refers to the base address of the array
and not to the values of any of the elements of the array.
Therefore, when we put prime in the cout statement,
what will be printed is the memory address of the first
element of the array. Clear enough?
One question is for sure here. If the name of the array
only refers to the base address of the array, how can we
access the elements of the array then? The elements of an
array are accessed by indexing via the array subscripting
operator. In C++, the indexing of one-dimensional arrays
starts from zero. Therefore, the first element of the
prime array in Program 2.3 is represented by
prime[0], the second element by prime[1] and so
on. Note that the last element of the array is prime[4]
not prime[5].
The array elements can also be accessed by using
variables. If i is an int variable with a value of 3,
prime[i] accesses the fourth element of the array.
Since arrays can also be accessed by variables, for-loops
are usually used to navigate through the elements of an
array. The following program will print the elements for
the prime array which Program 2.3 failed to do.
Program 2.4[Prints array].cpp
In the above program, for-loop is used to navigate
through the array elements. Since array indexing starts
from 0, the counter of the for-loop (i) started from 0.
4. By: Asaye Chemeda Email: asayechemeda@yahoo.com 19
Note that, in the above program, the counter loops until
the value of i is less than or equal to 5 by incrementing
its value by one. Run the program and note the output.
Now, the array elements are printed, right? What a relief!
But, how many numbers were printed on the output
screen? Six, right? But how many elements does the array
have? Only five, right? So, where did the sixth output
came from? The answer is simple. If a for-loop loops
from 0 to 5 inclusive, there will be six loops, not five.
Therefore, during the first loop when i = 0, prime
[0] which refers to the first element of the array, i.e., 2
will be printed. During the second loop when i = 1,
prime [1] which refers to the second element of the
array, i.e., 3 will be printed. Proceeding in a similar
manner, during the fifth loop when i = 4, the last
element of the prime array with a value of 11 will be
printed. But the for-loop goes for the sixth loop as well
and prints another value which is not the member of the
array. Therefore, if you want to navigate through and
manipulate only the array elements, you have to pay
attention while deciding the end values of the for-loop.
An interesting question here is: if the prime array is
defined only to have five elements, why didn’t the
compiler send an error message when the program tried
to access a sixth element which is not existing? The reason
is, C++ compilers do not check the array bounds. It is the
programmer’s responsibility to ensure that the array is
accessed and manipulated properly without violating the
array bounds. In Program 2.4, the program accessed a
sixth element of the array violating the boundary of the
array and a supposed value for that element was also
printed. You may ask what that printed value was then?
We have said that the elements of an array are stored in a
patterned contiguous memory locations with specific
starting and ending cells in the memory. When a C++
program is written to access and manipulate supposed
elements of an array outside the array’s boundary, the
compiler accesses any value from the memory outside
those starting and ending cells by using the pattern which
the compiler used to store the actual values of the array.
As a result, if the program tried to use those values which
are extracted from the memory location which is not
allocated for the array elements for calculations, wrong
results may be obtained. If the program tried to store
values in those wrong memory locations, data corruption
may result. This is a sensitive issue and great care should
be exercised to avoid such kind of out-of-array bounds
programming.
Now, let us now write a program which prints the sum
of two one-dimensional arrays. For this, we will define
three one-dimensional arrays each with three elements of
float data type. Two of the arrays will be used to store
values entered by the user from the console. These arrays
will be named vector1 and vector2. The third array
will be assigned with the sum of the other two arrays and
will be named vector3.
After what we discussed about one-dimensional arrays,
will it not be absurd if we write the program as below?
Program 2.5[Incorrect].cpp
In the above program, three arrays named vector1,
vector2 and vector3 were created. Is there anything
wrong in these array definitions? No. These definitions
are not the ones making the above program erroneous. If
you notice what we tried to do from line 11 through line
14, the program is indeed absurd. On line 11 of the
program, we tried to take vector1 as an input. If you
understand what vector1 represents, it is easy to
understand why the statement on this line is illegal. If not,
go back to Program 2.3 and read the explanation what
that program really executed. This also explains why the
rest lines in the Program 2.5 will not give us the result
which we wanted. Leaving the other illegal statements
aside, line 13 of the program tried to add the two arrays.
Such type of aggregate operations on arrays are not
allowed for array types with numerical values. The way
how lines 11 through 14 will be improved to get us the
result what we wanted becomes straight forward if we
follow the approach used in Program 2.4.
Another thing about the above program is the way how
the arrays were defined. As we said, there is nothing
wrong with the definition. However, let us see what kind
of drawbacks that such kind of array definition might
have and how we can improve it. Actually the drawbacks
are more pronounced if there are several arrays of the
same data type and number of elements within the
program. In the above program, all the arrays have the
same base data type (i.e., the data type of the individual
5. By: Asaye Chemeda Email: asayechemeda@yahoo.com 20
array elements) which is float. In addition, all the arrays
have three elements.
One of the problems with the above array definition is
that since all the arrays were defined with fixed values of
array elements, the number of array elements is not
dynamic. In the future, if you want to upgrade the sizes of
the arrays, you have to change the size of each individual
array one-by-one. Don’t you think that the program will
be more upgradable if we use a single variable
representing array size value for all the arrays having the
same sizes? Therefore, if there are several arrays with
similar properties and sizes, it is better to use variables as
array sizes instead of a fixed value. In the future, if you
want to upgrade the size of the arrays, you will only
change the value of that variable.
Another problem with the above array definition may
occur if we want to upgrade the array data types or if we
want to change the arrays into an advanced version in the
future. In addition, the array definition used in Program
2.5 will affect the program’s neatness if you have to define
several arrays of such kind with in the program.
Do you think that we are exaggerating the drawbacks of
the array definitions used in Program 2.5? We might be
but you may not know how the improvements which we
are going to talk about might make some C++ programs
more dynamic. So, let us have a program which improves
Program 2.5 and gives us the desired results. Here it is.
Program 2.6[Correct].cpp
In the above program, the statement on line 6 defines an
int variable which is initialized to a value of 3. The
keyword const states that the value of the
arraySize variable cannot be changed in the program.
This variable holds the sizes of the arrays. If we want to
change the sizes of each array, we will only change the
value of this variable. Imagine how time saving this could
be if we have several arrays and if we want to change their
sizes.
Line 7 of the program defines an array named vArray
with a size of arraySize and base data type of float.
The keyword typedef in this line makes the vArray
to be a data type of its own like other data types. As a
result, if some variable is of vArray data type, the
variable is an array with a size of arraySize and base
data type of float. If so, isn’t vArray exactly the same
as what the data type of arrays vector1, vector2 and
vector3 is? Therefore, on line 8 of the program, the
data arrays vector1, vector2 and vector3 are
defined to be of data type vArray. In the future, if we
want to change the data types of vector1, vector2
and vector3 to another data type, we will only change
vArray. Look how upgradable the program will be.
The statements from line 9 to line 16 of Program 2.6 are
used to enter user values for vector1 and vector2
arrays. Here, indexing is used to navigate through and
store the user values of the arrays’ elements. The for-loop
from line 18 to line 21 is used to get the elements of
vector3 as a sum of the corresponding elements of
vector1 and vector2 and print the obtained sum.
Here again, indexing is used to access all the elements of
the arrays. Note that in all the loops go from value of i
= 0 up to i < arraySize in all for-loops. As a
result, none of the array indexes are out of bounds. In
addition, if the size of the arrays change in the future,
there is no need to modify the for-loop. This is due to the
fact that the for-loops are expressed in terms of the
arraySize variable and as a result they are self-
adjustable in accordance with the array size.
We have now seen how array elements are accessed and
manipulated. Is that all what we have to know about
arrays? Not really. There are a lot more interesting
concepts regarding arrays. So, what are we waiting? Let us
go and grab them. Before going further, however, try to
recall what we discussed about functions. Particularly,
how parameter passing is done from one function to
another. I hope you understand where we are going with
this one, right? If you exactly guessed what we are going
to do next, it is passing arrays from one function to
another.
Passing Arrays as Parameters
In C++, arrays are passed to functions by reference
only. However, there is no need to put the & symbol in
the formal parameter list of the called function to express
that the array is received by reference. An interesting
6. By: Asaye Chemeda Email: asayechemeda@yahoo.com 21
question here is: what is the calling function passing to the
called function to pass an array? When a function calls
another function and wants to pass an array, what it has
to pass is the base address of the array. Of course, you
remember that the base address of the array is also
represented by the identifier used to define the array.
Another interesting concept about passing one-
dimensional arrays as parameters is that you can omit
mentioning the size of the array in the formal parameter
list of the called function. Think a little bit here. The
calling function only passed the base address of the array
and, the array size is omitted in the called function. You
might raise this question here: doesn’t the called function
have to know about the size of the array? The answer is,
it doesn’t have to. If the called function gets the base
address of the passed array, that is sufficient for a well-
written C++ program where out of bounds indexes are
taken care of inside the body of the function.
As we said, C++ compilers do not control if the program
tries to access values outside the memory location outside
the memory locations allocated for the array elements.
However, if the out of bounds indexes are avoided in the
body of the function, the base address is an adequate
input as an array. Therefore, what matters is what the
called function does inside its body based on that base
address.
Since array passing in C++ is done by reference, any
changes to the array in the called function will persist in
the calling environment. However, changes to a received
array in a function can be prevented by putting the
const keyword in front of the data type of array
parameter in the formal parameter list of the function
Let us apply the above concepts by writing a program.
This time, we will write a program which defines an array
named value with four elements with base data type of
double. This array will then be initialized by setting the
values of all its elements to zero by using a function
named initialize. Then, a function named
squareRoot will be called to assign each element of
the array with the square root of the index of the
corresponding element of the array. Finally, a function
named printArray will be called to print the
elements of the array. Since the printArray function
doesn’t have to change the values of the array elements,
the const keyword will be used. In the program, the
cmath header file will also be included since there are
mathematical functions which are called in the program.
Program 2.7[Correct].cpp
The contents of the above program are already explained
and there is no need to do it again. The output values are
shown below. The values represent the square root of the
first four whole numbers.
What do you think about the answer for the following
question? If passing arrays in C++ is done by reference
only, is returning arrays by functions is done by reference
only? The answer is no. C++ doesn’t allow returning
arrays at all; whether it is by value or by reference.
Have you noticed that we haven’t yet dealt with any
character arrays? We did that for a reason. The reason is
C++ gave special consideration for character arrays and
so will we.
Character arrays and C-Strings
Character arrays are arrays of elements with char data
type. Whereas, C-Strings are character arrays terminated
by the null character. As a result, character arrays are also
called null-terminated character arrays. The null character
7. By: Asaye Chemeda Email: asayechemeda@yahoo.com 22
is a non-printable character comprised of backslash and 0
(‘0’). The value of the null character is smaller than
any other character. In C-strings, the null character cannot
appear anywhere except at the end. If it does, all the
characters after the null character will not be considered
as part of the array.
The following might be your question after knowing that
character arrays are treated differently in C++. In what
way is C++ giving special consideration for character
arrays? The first way in which C++ gave special
consideration for character arrays, particularly for C-
strings, is by allowing character arrays to be initialized by
string literals. The string literals are sequences of
characters bounded by double quotation marks. If
character arrays are initialized in such a manner, the
compiler takes the arrays to be a null-terminated character
arrays with implicit null character at the end. Even if the
null character is not included between the double
quotation marks, the null character is considered as an
additional element to the array. Therefore, the size of the
character arrays should at least be the number of
characters between the double quotation marks plus one.
The second way in which C++ gave special consideration
for character arrays is by allowing aggregate operation on
character arrays, in contrast to arrays with numerical
values. As a result, the identifier used for character arrays
does not only refer to the base address of the array. If the
array is a C-string, the identifier of the C-string also refers
to all the characters in the character array combined. As a
result, you can print all the characters by using only the
identifier. You can also compare two C-strings by
comparing their identifiers.
C-strings or character arrays were the only intrinsic tools
by which you can handle strings. However, additional
class named string has also be devised to handle
strings. Strings which are declared as C-strings or by using
string class have their own capabilities and limitations.
For instance, it is not possible to assign C-strings once
they are declared or initialized. In addition, you can’t use
the ‘+’ sign to concatenate two C-strings. However, these
limitations of C-strings can be solved by using the
string class. And under certain circumstances, because
their simplicity while indexing, use of C-strings might
become very easy as compared to the strings declared by
string class. Therefore, using C-strings to handle
strings in your program is an optional task which you
pursue at your convenience.
Let us now see how the above concepts are incorporated
in a C++ program by writing one. Here is a program
involving character arrays and C-strings.
Program 2.8[Correct].cpp
In the above program, two character arrays (c1 and c2)
and one string variable (s) were defined. The character
array c1 is initialized with 11 character literals, i.e.,
characters bounded by single quotes. The character array
c2 is initialized by using a string literal. Therefore, c2 is
a C-string. There are again 11 characters between the
double quotation marks including the spaces. What do
you think is the number of elements in c2? If your answer
is 11, it means you have forgotten one necessary element
of C-strings - the null character. C-strings which are
initialized by string literals have this additional implicit
character. Therefore, the number elements in c2 is
actually 12, the 11 characters in the double quotes plus the
implicit null character. This indicates that character arrays
c1 and c2 are not equal even if they are composed of the
same characters.
As you know, when arrays are defined and initialized at
the same time, you may omit the sizes of the arrays. This
omission is very useful as you don’t have to change the
sizes of the arrays every time the number of initializing
elements changes. Since c1 and c2 were defined in such
a manner, there was no need to mention the number of
elements. However, if you mention the number of
elements for C-strings, the exact number of elements
including the null character should be specified. On line 8
of the program, a string variable s which has the same
content as c2 variable was also defined. These two
variables are equal and while writing a program, you can
use whichever way is convenient.
Line 9 through line 13 of the program show how
aggregate operation can be done on character arrays and
C-strings. When aggregate operation is done on character
arrays which are not null-terminated, caution must be
exercised as the identifier may refer to additional
characters which are not members of the array.
Therefore, the cout statement on line 9 of the program
might not get you the output which you expected. Line 10
of the program shows that indexing is also possible to
access and manipulate elements of character arrays or C-
strings. The statement on line 13 compares whether the
character array (c1) and the C-string (c2) are equal. The
output value for this line is 0 as c1 and c2 are not equal.
8. By: Asaye Chemeda Email: asayechemeda@yahoo.com 23
C++ has also pre-defined functions to manipulate
character arrays and C-Strings. In order to use these
functions, you need to include the cstring class in
your program. Among the list of functions in the
cstring class which are used to manipulate character
arrays and C-strings are:
strlen(s1) – gives the length of the s1. In case
of C-strings, the null character will not contribute for
the length s1.
strcpy(s1,s2) – copies the contents of s2 to
s1. Data corruption may occur if length of s1 is less
than s2.
strcat(s1,s2) – concatenates s2 on to the end
of s1.
strcmp(s1,s2) – returns 0 if s1 and s2 are the
same; less than 0 if s1<s2; greater than 0 if s1>s2.
Note that, since arrays are passed to function by reference
only, the changes which the above functions make to an
array is persistent after the functions are called.
Program 2.9[Correct].cpp
In the above program, the cstring class is included on
line 2. Character arrays c1 and c2 are defined on line 7
and line 8. Even if the number of initializing elements are
only 6, the size of c1 is set to 12 for a reason which you
will understand later. The C-string c3 seems to have two
string literals but it is a single character array. This is
because when C-strings are initialized by two or more
string literals without any punctuation marks between
them, the compiler will consider them as a single piece of
string literal.
On line 10 of the program, the pre-defined strcat
function is called to concatenate c2 on to the ends of c1.
After the function call, the character array c1 has all the
previous six elements of c1 and that of the six appended
c2 elements. Which means that c1 now has gained 6
additional elements and the total number of elements
becomes 12. That is why we declared c1 to have a
maximum of 12 elements on line 7. Note that, the changes
which are made to c1 after calling the strcat function
are persistent and c1 now becomes a null-terminated
string which is exactly the same as c3. This can be
confirmed by looking the output of the cout statement
on line 11 or analyzing the result of the strcmp function
on line 13. Line 12 of the program prints the length of
c3. Are you saying the length of c3 is 12 including the
null character? Or have you remembered that null
characters do not contribute for the length of C-strings
and answered it correctly to be 11? On line 14, the
contents of c2 were copied to c3 by the strcpy
function. This makes the contents of c3 to have that of
c2. The change can be noticed by observing the output
of the cout statement on line 15.
At this point, we can say that much of the concepts about
arrays, whether they are one-dimensional or multi-
dimensional, is already covered. Many of the points which
we discussed about one-dimensional arrays can be swiftly
applied for two- or any multi-dimensional arrays.
However, those concepts which are peculiar to multi-
dimensional arrays will be discussed next.
Two-Dimensional Arrays
Arrays having two-dimensions are called two-dimensional
arrays. We can say that two-dimensional arrays are built
from one or more one-dimensional arrays. Sizes of such
kind of arrays are characterized by two values: number of
rows and number of columns. As a result, two array
subscripting operators are used during the definition of
two-dimensional arrays - the first one for the number of
rows and the second one for the number of columns.
When two-dimensional arrays are declared and initialized
at the same time, the number of rows may be omitted but
specifying the number of columns is mandatory. If there
is no initialization during the declaration of two-
dimensional arrays, both the number of rows and number
of columns should be mentioned explicitly.
Elements of two-dimensional arrays can only be accessed
and manipulated through indexing. The indexing for both
rows and columns begins with 0. Elements of two-
dimensional arrays are accessed through indexing by using
two separate array subscripting operators. In the first
array subscripting operator, the row number of the
element to be accessed will be specified. In the second
array subscripting operator, the column number of the
element to be accessed will be specified. For instance, the
following indexing accesses the element in the second row
and third column of a two-dimensional array named
coefficient.
9. By: Asaye Chemeda Email: asayechemeda@yahoo.com 24
Aggregate operation on two-dimensional arrays may not
yield in expected results. The identifier used for two-
dimensional arrays refers to the base address of the array,
which the memory address of the first cell of the first
element of the array.
Two-dimensional arrays are also passed by reference only
and the base address is passed during a function call. Two-
dimensional arrays are saved in multiple rows of memory
locations, where the first memory locations in each row
are occupied by the elements in the first column of the
array. In the formal parameter list of the called function,
mentioning the number of columns is mandatory while
mentioning the number of rows is optional. This is
because the compiler needs to know where each row
starts from the number of columns but doesn’t care how
many rows there are as out of bounds indexing is not
checked in C++.
Two-dimensional character arrays can also be defined. If
the last element of each row is a null character, each row
of the array will be considered as a C-String. The aggregate
operations which can be done on C-strings can now be
done on each row of the null-terminated two-dimensional
character arrays. The C-strings can be extracted by using
the name of the two-dimensional array and one array
subscripting operator.
Program 2.10[Correct].cpp
In the above program, a two-dimensional array A having
four elements of double data type was defined and
initialized on line 8. Since it is mandatory to specify the
number of columns during declaration, the number of
columns was set to 2. Note that, during the initialization,
outer and inner braces were used. The inner braces are
only used for convenience of the programmer to identify
the elements in each row and they are optional. On line 9,
a two-dimensional character array C was defined and
initialized. The number of columns in two-dimensional
character arrays should at least be equal to the largest
number of characters including null characters on any
row. For array C, the second row which has the string
literal “dimensional” has the maximum number of
characters which is 12. Thus, the number of columns of
array C was set to be 12. Note that, it will have three rows.
One line 10 of the program, a one-dimensional character
array array1 was defined to have 24 elements. This
array will contain all the 24 characters in array C after
concatenation.
The cout statement on line 11 prints the element in the
first row and second column of array A. The output of
this statement should display a value of 2. On line 12, a
function named transpose was called and the base
address of array A was passed. The transpose function
transposes any array of double base data type which has
2 rows and 2 columns. In the formal parameter list of the
array, the number of columns was explicitly specified
while the optional number of rows wasn’t. Within the
body of the function, the content of the array aT which
is in the formal parameter list of the function is changed
and this change will persist in the environment where the
function is called, i.e., the main function. On line 13, the
element on the first row and second column of array A
was again printed to show that the transpose function
actually changed the contents of the array A and that the
change is reflected in the main function too. The output
of this statement should display a value of 3.
Each row of the two-dimensional character array C is a C-
string and can be accessed by specifying the row number
enclosed by only one array subscripting operator. On line
14, the pre-defined strcpy function of the cstring
class copies a string literal “Two-“ to the first row of
character array C. Note that after the strcpy function
is called, the first row of array C is no longer “One-“, it
is “Two-“. On line 15, another function named
initialize is called to initialize all the element of the
character array array1 with a null character. This also
shows how passing of character arrays is done.
On line 16, the pre-defined strcat function is called
three times to concatenate all the three rows of array C
with the initialized character array array1. Note that the
concatenation starts from the inner most strcat
function call. The first row of array C will be appended
10. By: Asaye Chemeda Email: asayechemeda@yahoo.com 25
first to the null character array array1, then the second
row of array C will be appended to the first row contained
in array1. The outer most strcat function appends
the third row of array C to array1 which already
contained the first and second rows of array C. When
array1 was printed on line 17, it should display all the
characters in arrays C concatenated one after another.
Our discussion on arrays is now complete. At this point,
you have to understand that arrays in C++ are not limited
to one or two-dimensions. You can define arrays of any
dimension in C++. If you understood what we discussed
in this chapter, it is easy to project those concepts for
arrays of any dimensions.
I hope this chapter was as interesting as the previous one.
Arrays also have great significance in C++ programming
and the concepts which we discussed in this chapter are
very useful. Therefore, you are on the way to be a good
programmer. However, the interesting concepts which we
already discussed are not the only ones in C++. There are
even more interesting topics which are remaining. If you
are ready, we will proceed to one of them.