You are on page 1of 10

CHAPTER TWO Let us now put restriction on the above program.

We will
ARRAYS still print all the values entered but we want to print them
Introduction in reverse order from the value entered last to the value
entered first. Can we handle this restriction with only one
Throughout the first chapter, with the exception where simple data type variable? Definitely not. We need to store
we used string data types few times, we mostly dealt with all the five values first to print them in reverse order. A
simple data types such as integers, floating-point values simple data type value can be accessed by using different
and characters. Those data types can store only a single variables (such as reference variables) but it can only store
value. For the problems which we tried to solve in that one value at a time. Therefore, only one simple data type
chapter, those data types were adequate. Because we variable is not adequate to print what we wanted. Is there
mostly dealt with variables which can be fully expressed another option? Simply, we can define five variables, we
by a single value. store the five integers in them and print their values in
However, in real world problems, we may be interested in reverse order. In that case, we will have the following
some structured arrangement of those simple data types. program.
To give you a simple example, if you can structurally Program 2.2[Correct].cpp
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 In the above program, we worked only with five integer
int array is made from all integer data types. The same is values. Defining five variables was not that difficult. Now
true for other simple data types as well. consider yourself having such kind of problem involving
hundreds or thousands of values? Will you keep on
Before looking into the details of arrays, we will see the defining the same number of variables as the number of
scenarios where arrays become useful. For this, we will values which you want to deal with? If that is the only
start from simple programs. option we have, you will say C++ is not that decent, right?
First, let us write a program which takes five integers and For such problems, however, C++ has provided us with
which prints their values as they are entered. Very easy. If the option to define only one array variable to store and
you remember for-loop, you can only define one int manipulate a number of simple data types of the same
variable. kind. In the above program, all the data types of the
variables are of int data type. As a result, a single array can
Program 2.1[Correct].cpp
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
In the above program, the variable x takes five integer the simple data types in only one dimension are called
values and prints them as they are entered. one-dimensional arrays. It is easy to guess what the other
arrays with more than one dimension would be called.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 16


Deciding what array dimension to use is usually a straight For instance, the following statement defines a one-
forward process. However, sometimes, it may become dimensional array named prime which can have up to 5
tricky. To discuss how you may select the array elements of int data type.
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
Like other simple data types, arrays can also be initialized.
in 100 rows and 1 column or 50 rows and 2 columns or
The initialization can be partial or complete. To initialize
in any other way where the product of the number of rows
one-dimensional arrays, you will assign the array
and number of columns will be equal to the number of
definition with array element initializing values separated
elements. As far as the memory requirement is concerned,
by comas and bounded by braces. The following
the required memory size is the same for equal number of
statement initializes, the elements of the prime array
the same data type elements whether the array is one-
defined above with the first five prime numbers.
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 With this initialization, the first element of the prime
dimensions where computation time is precious. array will be initialized by a value of 2, the second by a
value of 3 and so on.
Usually, if each element in an array is not be associated
with another value that describes that particular element, During initialization of one-dimensional arrays, the
you use one-dimensional array. If you want to store number of values between the braces cannot be greater
integers between 1 and 100, why would you use two- than the prescribed size of the array but it can be less. If
dimensional array while each element is independent of the number of values within the braces is exactly equal to
the other. Therefore in such cases, one-dimensional arrays the prescribed size of the array, the initialization is called
might be satisfactory. However, say, you want to store the full initialization. However, you can also initialize the
square of those integers as well along with the original array with fewer number of values than the prescribed
integers. In that case, each integer is associated with array size. This type of initialization is called partial
another value its square. In these case, two-dimensional initialization. In that case, the array will be initialized by
arrays become very handy and you will define a two- those values starting from the first element. The following
dimensional array. The same reasoning goes for creating statement partially initializes the prime array with two
multi-dimensional arrays. elements. Only the first and the second element of the
array will be initialized.
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 With the above initialization, the first element of the
dimension is called a column while the horizontal prime array will be initialized by a value of 2, the second
dimension is called a row. Therefore, when an array is by a value of 3 and the rest elements will take default
defined the number of rows and columns should be values.
explicitly stated.
Arrays can also be initialized without explicitly stating the
The one-dimensional arrays are the simplest types of size of the array. In that case, the compiler assumes the
arrays and we will start our discussion from them. array size is equal to the number of values between the
braces. Such type of array initialization is useful while
One-dimensional Arrays defining arrays with variable numbers of initialization
In C++, one-dimensional arrays have one column but any
elements. Because it is not necessary to adjust the arrays
number of rows. These arrays are defined like other size every time the array is initialized with different
simple data types. However, the number of rows that the numbers of initializing values. For instance, the following
array will have should be specified during the array
statement, which doesnt explicitly state the array size, is
definition. This is done by writing the array subscripting legal.
operator, [ ], with the array size in the middle after the
identifier. A typical array definition is done as follows:

When the compiler encounters the above statement, it


will allocate a memory space for an array called prime
By: Asaye Chemeda Email: asayechemeda@yahoo.com 17
having array size of five and initializes the five elements An interesting fact to note here is that, the identifier used
with the initializing values. for an array definition is associated with the memory
address of the first cell of the memory location where the
Is it getting boring? You might be saying this: we havent first element of the array is stored. The address of that
written any program involving arrays but we discussed a particular cell is known as the base address of the array.
lot about them. You are right. Let us now create a Which means that, the identifiers used for an array definition
function which involves one-dimensional array. refer to the base address of the array.
Specifically, let us write a program which prints the
elements of the prime array which will be initialized with Let us go back to our program and see what happened.
the first five prime numbers. Have you got any clue why we obtained those strange
combinations of numbers and characters now?
Program 2.3[Doesnot print Array].cpp 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 didnt 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?
In the above program, the prime array is defined and One question is for sure here. If the name of the array
initialized with on line 6. On line 7, we tried to print the only refers to the base address of the array, how can we
array elements. That is also what you are trying to print, access the elements of the array then? The elements of an
right? Run the program and see whether the numbers are array are accessed by indexing via the array subscripting
printed or not. operator. In C++, the indexing of one-dimensional arrays
starts from zero. Therefore, the first element of the
What did you get as an output? You got some strange prime array in Program 2.3 is represented by
combination of numbers and characters, right? Look back
prime[0], the second element by prime[1] and so
with what values you initialized the prime array and look
on. Note that the last element of the array is prime[4]
at the output. No relationship at all. Is the compiler wrong
not prime[5].
this time? Not really. You will understand what the
compiler printed after few discussion regarding how The array elements can also be accessed by using
arrays are stored in the main memory. variables. If i is an int variable with a value of 3,
prime[i] accesses the fourth element of the array.
When data items are defined in C++, the compiler will
allocate a memory space for the data items in the main Since arrays can also be accessed by variables, for-loops
memory. Arrays, being structured data types, are data are usually used to navigate through the elements of an
items which the compiler will allocate memory for. The array. The following program will print the elements for
the prime array which Program 2.3 failed to do.
main memory is comprised of ordered sequences of cells
each with memory size of one byte. Each cell has its own Program 2.4[Prints array].cpp
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 In the above program, for-loop is used to navigate
of the array one byte for char and bool, four bytes for through the array elements. Since array indexing starts
int and float and eight bytes for double. from 0, the counter of the for-loop (i) started from 0.
By: Asaye Chemeda Email: asayechemeda@yahoo.com 18
Note that, in the above program, the counter loops until three one-dimensional arrays each with three elements of
the value of i is less than or equal to 5 by incrementing float data type. Two of the arrays will be used to store
its value by one. Run the program and note the output. values entered by the user from the console. These arrays
will be named vector1 and vector2. The third array
Now, the array elements are printed, right? What a relief! will be assigned with the sum of the other two arrays and
But, how many numbers were printed on the output will be named vector3.
screen? Six, right? But how many elements does the array
have? Only five, right? So, where did the sixth output After what we discussed about one-dimensional arrays,
came from? The answer is simple. If a for-loop loops will it not be absurd if we write the program as below?
from 0 to 5 inclusive, there will be six loops, not five.
Therefore, during the first loop when i = 0, prime Program 2.5[Incorrect].cpp
[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 didnt the
compiler send an error message when the program tried In the above program, three arrays named vector1,
to access a sixth element which is not existing? The reason vector2 and vector3 were created. Is there anything
is, C++ compilers do not check the array bounds. It is the wrong in these array definitions? No. These definitions
programmers responsibility to ensure that the array is are not the ones making the above program erroneous. If
accessed and manipulated properly without violating the you notice what we tried to do from line 11 through line
array bounds. In Program 2.4, the program accessed a 14, the program is indeed absurd. On line 11 of the
sixth element of the array violating the boundary of the program, we tried to take vector1 as an input. If you
array and a supposed value for that element was also understand what vector1 represents, it is easy to
printed. You may ask what that printed value was then? understand why the statement on this line is illegal. If not,
go back to Program 2.3 and read the explanation what
We have said that the elements of an array are stored in a that program really executed. This also explains why the
patterned contiguous memory locations with specific rest lines in the Program 2.5 will not give us the result
starting and ending cells in the memory. When a C++ which we wanted. Leaving the other illegal statements
program is written to access and manipulate supposed aside, line 13 of the program tried to add the two arrays.
elements of an array outside the arrays boundary, the Such type of aggregate operations on arrays are not
compiler accesses any value from the memory outside allowed for array types with numerical values. The way
those starting and ending cells by using the pattern which how lines 11 through 14 will be improved to get us the
the compiler used to store the actual values of the array. result what we wanted becomes straight forward if we
As a result, if the program tried to use those values which follow the approach used in Program 2.4.
are extracted from the memory location which is not
allocated for the array elements for calculations, wrong Another thing about the above program is the way how
results may be obtained. If the program tried to store the arrays were defined. As we said, there is nothing
values in those wrong memory locations, data corruption wrong with the definition. However, let us see what kind
may result. This is a sensitive issue and great care should of drawbacks that such kind of array definition might
be exercised to avoid such kind of out-of-array bounds have and how we can improve it. Actually the drawbacks
programming. are more pronounced if there are several arrays of the
same data type and number of elements within the
Now, let us now write a program which prints the sum program. In the above program, all the arrays have the
of two one-dimensional arrays. For this, we will define same base data type (i.e., the data type of the individual
By: Asaye Chemeda Email: asayechemeda@yahoo.com 19
array elements) which is float. In addition, all the arrays change the sizes of each array, we will only change the
have three elements. value of this variable. Imagine how time saving this could
be if we have several arrays and if we want to change their
One of the problems with the above array definition is sizes.
that since all the arrays were defined with fixed values of
array elements, the number of array elements is not Line 7 of the program defines an array named vArray
dynamic. In the future, if you want to upgrade the sizes of with a size of arraySize and base data type of float.
the arrays, you have to change the size of each individual The keyword typedef in this line makes the vArray
array one-by-one. Dont you think that the program will to be a data type of its own like other data types. As a
be more upgradable if we use a single variable result, if some variable is of vArray data type, the
representing array size value for all the arrays having the variable is an array with a size of arraySize and base
same sizes? Therefore, if there are several arrays with data type of float. If so, isnt vArray exactly the same
similar properties and sizes, it is better to use variables as as what the data type of arrays vector1, vector2 and
array sizes instead of a fixed value. In the future, if you vector3 is? Therefore, on line 8 of the program, the
want to upgrade the size of the arrays, you will only data arrays vector1, vector2 and vector3 are
change the value of that variable. defined to be of data type vArray. In the future, if we
Another problem with the above array definition may want to change the data types of vector1, vector2
occur if we want to upgrade the array data types or if we and vector3 to another data type, we will only change
want to change the arrays into an advanced version in the vArray. Look how upgradable the program will be.
future. In addition, the array definition used in Program The statements from line 9 to line 16 of Program 2.6 are
2.5 will affect the programs neatness if you have to define used to enter user values for vector1 and vector2
several arrays of such kind with in the program.
arrays. Here, indexing is used to navigate through and
Do you think that we are exaggerating the drawbacks of store the user values of the arrays elements. The for-loop
the array definitions used in Program 2.5? We might be from line 18 to line 21 is used to get the elements of
but you may not know how the improvements which we vector3 as a sum of the corresponding elements of
are going to talk about might make some C++ programs vector1 and vector2 and print the obtained sum.
more dynamic. So, let us have a program which improves Here again, indexing is used to access all the elements of
Program 2.5 and gives us the desired results. Here it is. the arrays. Note that in all the loops go from value of i
= 0 up to i < arraySize in all for-loops. As a
Program 2.6[Correct].cpp 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.

In the above program, the statement on line 6 defines an Passing Arrays as Parameters
int variable which is initialized to a value of 3. The In C++, arrays are passed to functions by reference
keyword const states that the value of the only. However, there is no need to put the & symbol in
arraySize variable cannot be changed in the program. the formal parameter list of the called function to express
This variable holds the sizes of the arrays. If we want to that the array is received by reference. An interesting

By: Asaye Chemeda Email: asayechemeda@yahoo.com 20


question here is: what is the calling function passing to the Program 2.7[Correct].cpp
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: doesnt the called function
have to know about the size of the array? The answer is,
it doesnt 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 contents of the above program are already explained
the calling environment. However, changes to a received and there is no need to do it again. The output values are
array in a function can be prevented by putting the shown below. The values represent the square root of the
const keyword in front of the data type of array first four whole numbers.
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 What do you think about the answer for the following
values of all its elements to zero by using a function question? If passing arrays in C++ is done by reference
named initialize. Then, a function named only, is returning arrays by functions is done by reference
squareRoot will be called to assign each element of only? The answer is no. C++ doesnt allow returning
the array with the square root of the index of the arrays at all; whether it is by value or by reference.
corresponding element of the array. Finally, a function
named printArray will be called to print the Have you noticed that we havent yet dealt with any
character arrays? We did that for a reason. The reason is
elements of the array. Since the printArray function
C++ gave special consideration for character arrays and
doesnt have to change the values of the array elements,
so will we.
the const keyword will be used. In the program, the
cmath header file will also be included since there are Character arrays and C-Strings
mathematical functions which are called in the program. 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

By: Asaye Chemeda Email: asayechemeda@yahoo.com 21


is a non-printable character comprised of backslash and 0 Program 2.8[Correct].cpp
(\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
In the above program, two character arrays (c1 and c2)
consideration for character arrays, particularly for C-
and one string variable (s) were defined. The character
strings, is by allowing character arrays to be initialized by
array c1 is initialized with 11 character literals, i.e.,
string literals. The string literals are sequences of
characters bounded by single quotes. The character array
characters bounded by double quotation marks. If
c2 is initialized by using a string literal. Therefore, c2 is
character arrays are initialized in such a manner, the
compiler takes the arrays to be a null-terminated character a C-string. There are again 11 characters between the
arrays with implicit null character at the end. Even if the double quotation marks including the spaces. What do
you think is the number of elements in c2? If your answer
null character is not included between the double
quotation marks, the null character is considered as an is 11, it means you have forgotten one necessary element
additional element to the array. Therefore, the size of the of C-strings - the null character. C-strings which are
character arrays should at least be the number of initialized by string literals have this additional implicit
characters between the double quotation marks plus one. character. Therefore, the number elements in c2 is
actually 12, the 11 characters in the double quotes plus the
The second way in which C++ gave special consideration implicit null character. This indicates that character arrays
for character arrays is by allowing aggregate operation on c1 and c2 are not equal even if they are composed of the
character arrays, in contrast to arrays with numerical same characters.
values. As a result, the identifier used for character arrays
does not only refer to the base address of the array. If the As you know, when arrays are defined and initialized at
array is a C-string, the identifier of the C-string also refers the same time, you may omit the sizes of the arrays. This
to all the characters in the character array combined. As a omission is very useful as you dont have to change the
result, you can print all the characters by using only the sizes of the arrays every time the number of initializing
identifier. You can also compare two C-strings by elements changes. Since c1 and c2 were defined in such
comparing their identifiers. a manner, there was no need to mention the number of
elements. However, if you mention the number of
C-strings or character arrays were the only intrinsic tools elements for C-strings, the exact number of elements
by which you can handle strings. However, additional including the null character should be specified. On line 8
class named string has also be devised to handle of the program, a string variable s which has the same
strings. Strings which are declared as C-strings or by using content as c2 variable was also defined. These two
string class have their own capabilities and limitations. variables are equal and while writing a program, you can
For instance, it is not possible to assign C-strings once use whichever way is convenient.
they are declared or initialized. In addition, you cant use
the + sign to concatenate two C-strings. However, these Line 9 through line 13 of the program show how
limitations of C-strings can be solved by using the aggregate operation can be done on character arrays and
C-strings. When aggregate operation is done on character
string class. And under certain circumstances, because
arrays which are not null-terminated, caution must be
their simplicity while indexing, use of C-strings might exercised as the identifier may refer to additional
become very easy as compared to the strings declared by characters which are not members of the array.
string class. Therefore, using C-strings to handle Therefore, the cout statement on line 9 of the program
strings in your program is an optional task which you might not get you the output which you expected. Line 10
pursue at your convenience. of the program shows that indexing is also possible to
access and manipulate elements of character arrays or C-
Let us now see how the above concepts are incorporated strings. The statement on line 13 compares whether the
in a C++ program by writing one. Here is a program character array (c1) and the C-string (c2) are equal. The
involving character arrays and C-strings. output value for this line is 0 as c1 and c2 are not equal.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 22


C++ has also pre-defined functions to manipulate maximum of 12 elements on line 7. Note that, the changes
character arrays and C-Strings. In order to use these which are made to c1 after calling the strcat function
functions, you need to include the cstring class in are persistent and c1 now becomes a null-terminated
your program. Among the list of functions in the string which is exactly the same as c3. This can be
cstring class which are used to manipulate character confirmed by looking the output of the cout statement
arrays and C-strings are:
on line 11 or analyzing the result of the strcmp function
strlen(s1) gives the length of the s1. In case on line 13. Line 12 of the program prints the length of
of C-strings, the null character will not contribute for c3. Are you saying the length of c3 is 12 including the
the length s1. null character? Or have you remembered that null
strcpy(s1,s2) copies the contents of s2 to characters do not contribute for the length of C-strings
s1. Data corruption may occur if length of s1 is less and answered it correctly to be 11? On line 14, the
than s2. contents of c2 were copied to c3 by the strcpy
function. This makes the contents of c3 to have that of
strcat(s1,s2) concatenates s2 on to the end
of s1. c2. The change can be noticed by observing the output
of the cout statement on line 15.
strcmp(s1,s2) returns 0 if s1 and s2 are the
same; less than 0 if s1<s2; greater than 0 if s1>s2. At this point, we can say that much of the concepts about
arrays, whether they are one-dimensional or multi-
Note that, since arrays are passed to function by reference
dimensional, is already covered. Many of the points which
only, the changes which the above functions make to an
we discussed about one-dimensional arrays can be swiftly
array is persistent after the functions are called.
applied for two- or any multi-dimensional arrays.
Program 2.9[Correct].cpp 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
In the above program, the cstring class is included on
is no initialization during the declaration of two-
line 2. Character arrays c1 and c2 are defined on line 7
dimensional arrays, both the number of rows and number
and line 8. Even if the number of initializing elements are
of columns should be mentioned explicitly.
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 Elements of two-dimensional arrays can only be accessed
string literals but it is a single character array. This is and manipulated through indexing. The indexing for both
because when C-strings are initialized by two or more rows and columns begins with 0. Elements of two-
string literals without any punctuation marks between dimensional arrays are accessed through indexing by using
them, the compiler will consider them as a single piece of two separate array subscripting operators. In the first
string literal. array subscripting operator, the row number of the
element to be accessed will be specified. In the second
On line 10 of the program, the pre-defined strcat
array subscripting operator, the column number of the
function is called to concatenate c2 on to the ends of c1.
element to be accessed will be specified. For instance, the
After the function call, the character array c1 has all the following indexing accesses the element in the second row
previous six elements of c1 and that of the six appended and third column of a two-dimensional array named
c2 elements. Which means that c1 now has gained 6 coefficient.
additional elements and the total number of elements
becomes 12. That is why we declared c1 to have a

By: Asaye Chemeda Email: asayechemeda@yahoo.com 23


Aggregate operation on two-dimensional arrays may not columns was set to 2. Note that, during the initialization,
yield in expected results. The identifier used for two- outer and inner braces were used. The inner braces are
dimensional arrays refers to the base address of the array, only used for convenience of the programmer to identify
which the memory address of the first cell of the first the elements in each row and they are optional. On line 9,
element of the array. a two-dimensional character array C was defined and
initialized. The number of columns in two-dimensional
Two-dimensional arrays are also passed by reference only
character arrays should at least be equal to the largest
and the base address is passed during a function call. Two-
number of characters including null characters on any
dimensional arrays are saved in multiple rows of memory
row. For array C, the second row which has the string
locations, where the first memory locations in each row
literal dimensional has the maximum number of
are occupied by the elements in the first column of the
characters which is 12. Thus, the number of columns of
array. In the formal parameter list of the called function,
array C was set to be 12. Note that, it will have three rows.
mentioning the number of columns is mandatory while
One line 10 of the program, a one-dimensional character
mentioning the number of rows is optional. This is
array array1 was defined to have 24 elements. This
because the compiler needs to know where each row
array will contain all the 24 characters in array C after
starts from the number of columns but doesnt care how
many rows there are as out of bounds indexing is not concatenation.
checked in C++. The cout statement on line 11 prints the element in the
Two-dimensional character arrays can also be defined. If first row and second column of array A. The output of
the last element of each row is a null character, each row this statement should display a value of 2. On line 12, a
of the array will be considered as a C-String. The aggregate function named transpose was called and the base
operations which can be done on C-strings can now be address of array A was passed. The transpose function
done on each row of the null-terminated two-dimensional transposes any array of double base data type which has
character arrays. The C-strings can be extracted by using 2 rows and 2 columns. In the formal parameter list of the
the name of the two-dimensional array and one array array, the number of columns was explicitly specified
subscripting operator. while the optional number of rows wasnt. Within the
body of the function, the content of the array aT which
Program 2.10[Correct].cpp 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
In the above program, a two-dimensional array A having three times to concatenate all the three rows of array C
four elements of double data type was defined and with the initialized character array array1. Note that the
initialized on line 8. Since it is mandatory to specify the concatenation starts from the inner most strcat
number of columns during declaration, the number of function call. The first row of array C will be appended

By: Asaye Chemeda Email: asayechemeda@yahoo.com 24


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.

By: Asaye Chemeda Email: asayechemeda@yahoo.com 25

You might also like