Chapter 5 C++ Array
Chapter 5 C++ Array
ARRAYS, POINT-
ERS AND STRINGS
ARRAYS
ARRAYS
An array allows you to store and work with mul-
tiple values of the same data type.
An array works like a variable that can store a
group of values, all of the same type.
An array must be declared before it is used.
A typical declaration for an array in C++ is:
type name [Size];
where type is a valid object type (int, float...),
name is a valid variable identifier and the
Size field, that is enclosed within brackets [ ], speci-
fies how many of these elements the array contains.
… ARRAYS
Here is an example of an array of integers:
int hours[6];
The name of this array is hours.
The number inside the brackets is the array’s size
declarator.
It indicates the number of elements, or values, the array can
hold.
The hours array can store six integer elements.
This is depicted in the following figure.
… ARRAYS
An array’s size declarator must be a constant in-
teger expression with a value greater than zero.
const int SIZE = 6;
int hours[SIZE];
Arrays of any data type can be defined.
The following are all valid array definitions:
float temperature[100]; // Array of 100 floats
char letter[26]; // Array of 26 characters
long unit[50]; // Array of 50 long integers
double size[1200]; // Array of 1200 doubles
Accessing Array Elements
The format is the following:
name[index]
The individual elements of an array are assigned unique
subscripts.
Subscript numbering in C++ always starts at zero.
The subscript of the last element in an array is array size
minus one.
This means that in the array int hours[6];
the element hours[6] does not exist.
The last element in the array is hours[5].
… Accessing Array Elements
Assume the following two arrays have been defined.
int doctorA[5]; // Holds the number of patients seen by Dr. A on each of 5
days.
int doctorB[5]; // Holds the number of patients seen by Dr. B on each of 5
days.
The following are all legal assignment statements.
doctorA[0] = 31; // doctorA[0] now holds 31.
doctorA[1] = 40; // doctorA[1] now holds 40.
doctorA[2] = doctorA[0]; // doctorA[2] now also holds
31.
doctorB[0] = doctorA[1]; // doctorB[0] now holds 40.
However, the following statements are not legal.
doctorA = 152; // Illegal!
doctorB = doctorA; // Illegal!
… Accessing Array Elements
For example, consider the following array:
int billy [] = { 16, 2, 1, 40, 12 };
To store the value 5 in the third element of billy:
billy[2] = 5;
To pass the value of the third element of billy to the variable a, we
could write:
a = billy[2];
The following are valid operations with arrays:
// declaration of a new Array (begins with a type name)
int billy[5];
// access to an element of the Array.
billy[2] = 5;
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;
… Accessing Array Elements
The following program demonstrates how we can access array ele-
ments and perform operations using those elements.
#include <iostream.h>
int billy [ ] = {10, 20, 30, 400, 12000};
int n, result = 0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
result += billy[n];
cout << result;
return 0;
}
Output:
12460
Array Initialization
Arrays may be initialized when they are defined or with separate as-
signment statements.
By writing separate assignment statements for the individual ele-
ments of an array:
const int NUM_MON = 12;
int days[NUM_MON];
days[0] = 31; // January
days[1] = 28; // February
……………..
days[9] = 31; // October
days[10] = 30; // November
days[11] = 31; // December
By using an initialization list, all the elements of the array can be
easily initialized when the array is created.
For example: the following statement defines the days array and ini-
tializes it with the values:
int days[NUM_MON] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
… Array Initialization
For example, consider the following pro-
gram segment.
const int NUM_MON = 12;
int days[NUM_MON] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int month = 0; month < NUM_MON; month++)
{
cout << "Month " << (month + 1) << " has ";
cout << days[month] << " days.\n";
}
Partial Array Initialization
An initialization list cannot have more values than the ar-
ray has elements, but it may have fewer values than
there are elements.
i.e. C++ does not require a value for every element.
It’s possible to only initialize some part of an array, such
as
int numbers[7] = {1, 2, 4, 8};
This definition only initializes the first four elements of a seven
element array:
… Partial Array Initialization
If an array is partially initialized, the uninitialized elements will be set
to zero for numeric arrays or to the null character for character ar-
rays.
The following program segment shows the contents of the numbers
array after it is partially initialized.
const int SIZE = 7;
int numbers[SIZE] = {1, 2, 4, 8}; // Initialize the first 4 elements.
for (int index = 0; index < SIZE; index++)
cout << numbers[index] << " “ << endl;
This fragment displays the contents of the array as follows:
1248000
If you leave an element uninitialized, you must leave all the ele-
ments that follow it uninitialized as well.
For example, the following is not legal:
int array[6] = {2, 4, , 8, , 12}; // NOT Legal!
Implicit Array Sizing
It’s possible to define an array without specifying its size,
providing an initialization list that includes a value for ev-
ery element.
C++ automatically makes the array large enough to hold
all the initialization values.
For example, the following definition creates an array
with five elements:
double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};
Because the size declarator is omitted, C++ counts the
number of items in the initialization list and gives the ar-
ray that many elements.
Note: You must specify an initialization list if you leave
out the size declarator. Otherwise, C++ doesn’t know
how large to make the array.
Processing Array Contents
For example, the following statement multiplies hours[3] by the vari-
able rate:
pay = hours[3] * rate;
The following are examples of pre-increment and post-increment
operations on array elements:
int score[5] = {7, 8, 9, 10, 11};
++score[2]; // Pre-increment operation on the value in score[2]
score[4]++; // Post-increment operation on the value in score[4]
Array elements can also be used in relational expressions.
For example, the following if statement tests cost[20] to deter-
mine if it is less than cost[0]:
if (cost[20] < cost[0])
And the following statement sets up a while loop to iterate as
long as value[place] does not equal 0:
while (value[place] != 0)
Processing Strings
Strings are internally stored as arrays of characters.
They are different from other arrays in that the elements can either be
treated as a set of individual characters or
can be used as a single entity.
The following sample code defines a character object and treats it as a sin-
gle entity, inputting it and displaying it as a single unit.
char name[10];
cout << "Enter your name: ";
cin >> name;
cout << "Hello, " << name << endl;
We can process the string character by character.
If "Warren" were entered, for example, the statement
cout << name[0]; would print the letter W,
cout << name[1]; would print the letter a, and so forth.
Multidimensional
Arrays
Two-Dimensional Arrays
An array is useful for storing and working with a set of
data.
A 2D-array is useful for storing multiple sets of data.
It’s best to think of a two-dimensional array as a table
having rows and columns of elements.
To define a 2D-array, two size declarators are required:
the first one is for the number of rows and
the second one is for the number of columns.
For processing the information in a two-dimensional ar-
ray, each element has two subscripts:
one for its row and
another for its column.
… Two-Dimensional Arrays
In the score array, the elements in row 0 are referenced as:
score[0][0]
score[0][1]
score[0][2]
score[0][3]
The elements in row 1 are
score[1][0]
score[1][1]
score[1][2]
score[1][3]
And the elements in row 2 are
score[2][0]
score[2][1]
score[2][2]
score[2][3]
… Two-Dimensional Arrays
For example, the following statement assigns the value 92.25 to the element at row 2,
column 1 of the score array:
score[2][1] = 92.25;
And the following statement displays the element at row 0, column 2:
cout << score[0][2];
When initializing a two-dimensional array, it helps to enclose each row’s initialization list in a set
of braces. Here is an example:
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
The same statement could also be written as
int hours[3][2] = {{8, 5},
{7, 9},
{6, 3}};
In either case, the values are assigned to hours in the following manner:
hours[0][0] is set to 8
hours[0][1] is set to 5
hours[1][0] is set to 7
hours[1][1] is set to 9
hours[2][0] is set to 6
hours[2][1] is set to 3
… Two-Dimensional Arrays
The extra braces that enclose each row’s initialization list
are optional.
Both of the following statements perform the same initial-
ization:
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
int hours[3][2] = {8, 5, 7, 9, 6, 3};
The braces give you the ability to leave out initializers:
int table[3][2] = {{1}, {3, 4}, {5}};
In the above array definition:
table[0][0] is initialized to 1,
table[1][0] is initialized to 3,
table[1][1] is initialized to 4, and
table[2][0] is initialized to 5.
The uninitialized elements, table[0][1] and table[2][1], are
automatically set to zero.
POINTERS
Address (dereference) operator (&)
The address operator (&) returns the memory address of
a variable.
Suppose the following variable declaration:
float amount;
When the address operator (&) is placed in front of a
variable name, it returns the address of that variable.
Here is an expression that returns the address of the
variable amount:
&amount
Here is a statement that displays the variable’s ad-
dress on the screen:
cout << &amount;
… Address (dereference) operator (&)
For example the statement:
ted = &andy;
would assign to variable ted the address of variable andy,
When preceding the name of the variable andy with the
ampersand (&) character we are talking about its ad-
dress in memory not its content.
We are going to suppose that andy has been placed in
the memory address 1776 and that we write the follow-
ing:
andy = 25;
fred = andy;
ted = &andy;
… Address (dereference) operator (&)
andy = 25;
fred = andy;
ted = &andy;
We have assigned:
to fred the content of variable andy, but
to ted the address in memory where the value of andy is stored
The reason is that in the allocation of ted we have pre-
ceded andy with an ampersand (&) character.
The variable that stores the address of another variable
(like ted in the previous example) is what we call a
pointer.
Pointer Variables
Pointer variables are often called pointers
They are designed to hold memory addresses.
Pointers are special variables that C++ provides
for working with memory addresses.
Just like int variables are designed to hold and
work with integers, pointer variables are de-
signed to hold and work with addresses.
… Pointer Variables
The definition of a pointer variable looks like the
following:
int *ptr;
The asterisk indicates that ptr is a pointer variable.
The int data type indicates that ptr can be used to
hold the address of an integer variable.
The declaration statement above would read “ptr
is a pointer to an int.”
Note: In this definition, the word int does not
mean that ptr is an integer variable.
Remember, pointers only hold one thing: ad-
dresses.
Declaring Pointer Variables
It is necessary to specify which data type a pointer points
to when declaring it.
Therefore, the declaration of pointers follows this form:
type * pointer_name;
where type is the type of data pointed, not the type of the pointer
itself.
For example:
int * number;
char * character;
float * greatnumber;
they are three declarations of pointers.
The following statement declares the two pointers of the
previous example putting an asterisk (*) for each pointer.
int *p1, *p2;
… Declaring Pointer Variables
In the following statements:
int x = 25;
int *ptr;
ptr = &x;
The variable x is an int, while ptr is a pointer to an int.
The variable x is initialized with 25, while ptr is as-
signed the address of x.
the variable x is located at memory address 0x7e00
and contains the number 25,
the pointer ptr contains the address 0x7e00.
In essence,” ptr “points to the variable x.
Reference (Indirection ) operator (*)
With pointer variables you can indirectly manipulate data stored in
other variables.
Using a pointer we can directly access the value stored in the vari-
able pointed by it.
This is done by preceding the pointer identifier with the reference
operator asterisk (*)
Therefore, if we write:
andy = 25;
fred = andy;
ted = &andy;
beth = *ted;
beth would take
the value 25,
since ted is 1776,
and the value pointed
by 1776 is 25.
… Reference (Indirection ) operator (*)
andy = 25;
ted = &andy;
beth = *ted;
You must clearly differentiate that:
ted stores 1776,
*ted refers to the value stored in the address 1776, that is 25.
Notice the difference of including or not including the reference as-
terisk:
beth = ted; // beth equal to ted ( 1776 )
beth = *ted; // beth equal to value pointed by ted ( 25 )
Consider the following statements:
andy = 25;
ted = &andy;
all the following expressions are true:
andy == 25 &andy == 1776
ted == 1776 *ted == 25
*ted == andy
… Reference (Indirection ) operator (*)