Home

Arrays and Fundamental Strings

 

Fundamentals of Arrays

We have learned to use two types of variables: identifiers created using C++ data types and programmer defined objects. A regular variable is declared using an integer, a floating point number, or a character, etc. To create more advanced objects, we learned to combine variables and create a group called a class. We also know that a class can have as many varied and types of variables as we see fit. We learned to use enumerations to create a group of constant integers recognized by their names and position in the group. We will now explore one more system of grouping variables or objects into a new variable.

Introduction to Arrays

An array is a special data type used to create a group of variables of the same type. A group of words is considered an array of words. A group of books on a book shelf is an array of books. A group of cars parked on the mall is an array of cars. Here are examples of arrays:

Array
An array of letters An array of airplanes
Array Array
An array of cards An array of bugs

An array resembles an enumerator in that both are used to represent a group of items of the same time. They differ in that, while an enumerator groups only constant integers, one type of array can consist of integers; another type of array could be made of floating point numbers. Yet another array could be made of objects (classes or structures).

An array and a class have this in common. Both can represent a group of items of different types. As a difference, all items of an array must be of the same data type or the same class; by contrast, an object can consist of different variables of any type.

  Enumerator Object Array
Similarities Items of same type Grouping of items Items of the same type
Differences Constant integers Items made of different variables All items must be of the same type

An array is not a new data type. It simply provides a technique of creating a group of variables of the same type. Using an array, you can create a single variable, give it a name and tell it how many items will be in the group.

Declaring Arrays

An array is a group of contiguous items of the same kind or the same data type. Instead of defining them individually, you create one name and tell the compiler that the name will represent a group of items. The syntax of creating an array is

DataType ArrayName[Dimension];

The DataType is any of the data types we have learned so far. It could be an integer, a floating point variable, or a character, etc. The following could be arrays:

int ArrayName[Dimension];
float ArrayName[Dimension];
double ArrayName[Dimension];
unsigned int ArrayName[Dimension];

The name of an array follows the same rules we have applied to other variables. The above arrays could be declared as:

int PlayerPosition[Dimension];
float Radius[Dimension];
double DistanceToWork[Dimension];
unsigned int NumberOfStudents[Dimension];

Consider a list of players in a Handball game. You know that only six players are on the court at a time. Physically (but not literally), the group of items can be represented as follows:

HandballPlayers Position-1 Position-2 Position-3 Position-4 Position-5 Position-6

Besides its data type and its name, an array is also recognized by the number of items that compose the group. This represents the array’s dimension, which is an integer. The dimension is set between square brackets.. The number of players in the Handball team represents the dimension of the array; this would be 6. Such an array would be declared as:

int HandballPlayers[6];

Of course, in another game, the array representing the players would have a different dimension, depending on the sport. Here is an example:

int SoccerPlayers[11];

If you are uncertain of the number of members that compose an array, set the maximum dimension possible, but not too high. For example, different people have different lengths of names. Therefore, to declare an array that would represent a first name, you can use char FirstName[20]. Examples of the previous arrays would be:

int PlayerPosition[11];
float Radius[6];
double DistanceToWork[100];
unsigned int NumberOfStudents[3600];

As an array represents a group of items, all of the items must be of the same type. For example, if you want to declare an array that represents letters, since we know that the letters are identified in C++ using the char data type, we could write:

char Country[20];

In this case, all of the items of the Country array must be valid letters. On the other hand, another type of array that represents distances between cities can be declared as:

double Distances[22];

In this case, each item that is part of the Distances array must be a valid floating-point number.

Initializing an Array

An item that is part of an array is referred to as a member of the array. It is very important to understand the difference between an array's dimension and an array's member. The dimension defines the number of members of an array. For example, an array that represents the players of a football (soccer) game has a dimension of 11 and could be defined as int Players[11]. In this case, the array is made of 11 integer members; this means each member of the array has to be an integer. These members have their own values. For example, a goalkeeper would have a value of 1 (or 16), a middle-fielder would be Number 10, a right-winger would be Number 7. By contrast, if you declare an array as double SquareRoots[24], this represents a group of 24 (which is an integer) values that each is a double-precision number. One of the members could have a value of 11.180 while another member would hold a value of 68.425.

Each member of an array can be retrieved using its position. The members of an array are arranged starting at position 0, followed by position 1, then position 2, etc. This system of counting is referred to as "zero-based" because the counting starts at 0. The first item, at position 0, is identified as HandballPlayers[0] = 22; the second item, at position 1, is HandballPlayers [1] = 5. You can use the cout operator to display the value of a member of an array.

To initialize an array, you can assign an individual value to each member. Imagine an array of 7 numbers that represent square root values. You can declare the array as:

double SquareRoot [7];

Then you can initialize each member using its position and assigning it the desired value:

SquareRoot[0] = 6.480;
SquareRoot[1] = 8.306;
SquareRoot[2] = 2.645;
SquareRoot[3] = 20.149;
SquareRoot[4] = 25.729;
SquareRoot[5] = 3.00;
SquareRoot[6] = 1.73;

As we have learned, you can use each member’s position to display its value. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double SquareRoot[7];

    // Initializing individual members of an array
    SquareRoot[0] = 6.480;
    SquareRoot[1] = 8.306;
    SquareRoot[2] = 2.645;
    SquareRoot[3] = 20.149;
    SquareRoot[4] = 25.729;
    SquareRoot[5] = 3.00;
    SquareRoot[6] = 1.73;

    // Displaying square roots
    cout << "Square Roots";
    cout << "\nRoot 1 = " << SquareRoot[0]
         << "\nRoot 2 = " << SquareRoot[1]
         << "\nRoot 3 = " << SquareRoot[2]
         << "\nRoot 4 = " << SquareRoot[3]
         << "\nRoot 5 = " << SquareRoot[4]
         << "\nRoot 6 = " << SquareRoot[5]
         << "\nRoot 7 = " << SquareRoot[6];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Square Roots
Root 1 = 6.48
Root 2 = 8.306
Root 3 = 2.645
Root 4 = 20.149
Root 5 = 25.729
Root 6 = 3
Root 7 = 1.73

Press any key to continue...

The advantage of initializing the members individually is that you do not have to follow their order, as long as you specify their position. The above members could have been initialized in any order you want:

SquareRoot[3] = 20.149;
SquareRoot[6] = 1.73;
SquareRoot[0] = 6.480;
SquareRoot[4] = 25.729;
SquareRoot[1] = 8.306;
SquareRoot[5] = 3.00;
SquareRoot[2] = 2.645;

In the same way you can display the value of any member of the array anytime, using its position:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double SquareRoot[7];

    // Initializing individual members of an array
    SquareRoot[3] = 20.149;
    SquareRoot[6] = 1.73;
    SquareRoot[0] = 6.480;
    SquareRoot[4] = 25.729;
    SquareRoot[1] = 8.306;
    SquareRoot[5] = 3.00;
    SquareRoot[2] = 2.645;

    // Displaying square roots
    cout << "Square Roots";
    cout << "\nRoot 6 = " << SquareRoot[5]
         << "\nRoot 3 = " << SquareRoot[2]
         << "\nRoot 1 = " << SquareRoot[0]
         << "\nRoot 5 = " << SquareRoot[4]
         << "\nRoot 7 = " << SquareRoot[6]
         << "\nRoot 4 = " << SquareRoot[3]
         << "\nRoot 2 = " << SquareRoot[1];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Square Roots
Root 6 = 3
Root 3 = 2.645
Root 1 = 6.48
Root 5 = 25.729
Root 7 = 1.73
Root 4 = 20.149
Root 2 = 8.306

Press any key to continue...

Another technique you can use to initialize the members of an array is by using their order of appearance. This allows you to initialize the array as a whole. While the dimension of an array is set between square brackets, the members of an array are defined between an opening curly bracket '{', and a closing one '}'. The declaration ends with a semi-colon. Our array of square roots could be initialized as follows:

double SquareRoot[7] = { 6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73 };

Each member of the array would receive the value that corresponds to its position. You can then display their values using their position:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array
    double SquareRoot[7] = {6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73};

    // Displaying square roots
    cout << "Square Roots";
    cout << "\nRoot 1 = " << SquareRoot[0]
         << "\nRoot 2 = " << SquareRoot[1]
         << "\nRoot 3 = " << SquareRoot[2]
         << "\nRoot 4 = " << SquareRoot[3]
         << "\nRoot 5 = " << SquareRoot[4]
         << "\nRoot 6 = " << SquareRoot[5]
         << "\nRoot 7 = " << SquareRoot[6];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Using a for loop to count the members of the array, the above code could have been written:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array
    double SquareRoot[7] = {6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73};

    // Displaying the values of members of the array
    cout << "Square Roots";
    for(int n = 0; n < 6; n++)
        cout << "\nRoot " << n + 1 << " = " << SquareRoot[n];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

When you initialize the array as a whole, you cannot switch the positions of the members because you cannot access them. The advantage is that the declaration is more concise. Since the members of the array are set by their position, even if you declare the array as a whole, you can still access an individual member using its position, in any order:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array
    double SquareRoot[7] = {6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73};

    // Displaying the values of members of the array
    cout << "Square Roots";
    cout << "\nRoot 6 = " << SquareRoot[5]
         << "\nRoot 3 = " << SquareRoot[2]
         << "\nRoot 1 = " << SquareRoot[0]
         << "\nRoot 5 = " << SquareRoot[4]
         << "\nRoot 7 = " << SquareRoot[6]
         << "\nRoot 4 = " << SquareRoot[3]
         << "\nRoot 2 = " << SquareRoot[1];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Processing an Array

Since the dimension of an array is a constant integer, sometimes it is more convenient and professional to declare such a constant. This allows more control over the dimension of the array especially when or if you decide to change the dimension. You can easily locate the constant variable that represents the dimension of the array and change it there. Such a constant must be declared before using it; this is usually done on the top section of the function that uses the array. Therefore, the declaration of the array above would be

const int NbrOfPlayers = 6;
int HandballPlayers[NbrOfPlayers] = {22, 5, 12, 34, 2, 8};

When initializing an array, you do not have to set the dimension of the array. You can just start initializing the members by their position. When you finish, the compiler would figure out how many members are in the array. After initializing the array, you do not have to access all of its members, you can just retrieve the values of those you need. Our SquareRoot array consists of 7 members, using the following program, you can display the values of less than 7 members:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array double
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73 };

    // Displaying the values of members of the array
    cout << "Square Roots";
    for(int n = 0; n < 4; n++)
        cout << "\nRoot " << n + 1 << " = " << SquareRoot[n];


    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Square Roots
Root 1 = 6.48
Root 2 = 8.306
Root 3 = 2.645
Root 4 = 20.149

Press any key to continue...

Notice that although our array is made of 7 members, we asked the compiler to display only 4 of their values.

You should always know the dimension of an array or at least have an approximate view of the number of its members. When accessing the members of an array, if you request values of members that are not of the group, the compiler would provide garbage values. Our SquareRoot array has 7 members. If you try to access more than 7 members, the result would be unpredictable:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array double
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729, 3.00, 1.73 };

    // Displaying the values of members of the array
    cout << "Square Roots";
    for(int n = 0; n < 12; n++)
        cout << "\nRoot " << n + 1 << " = " << SquareRoot[n];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Square Roots
Root 1 = 6.48
Root 2 = 8.306
Root 3 = 2.645
Root 4 = 20.149
Root 5 = 25.729
Root 6 = 3
Root 7 = 1.73
Root 8 = 6.81439e-66
Root 9 = 5.58683e-306
Root 10 = 4.63572e-317
Root 11 = nan
Root 12 = 2.64221e-308

Press any key to continue...

Instead of guessing the dimension of an array, an alternative is to perform an operation that would find the dimension of the array, then use that dimension. To find the dimension of an array, use the sizeof operator. This is done by dividing the size of the array by the size of its data type. For example, if you have an array of integer numbers initialized as follows:

int BooksPages[] = { 122, 540, 38, 228, 96, 152, 304, 882 };

You can get the number of members of the array using the following operation:

int RecordSize = sizeof(BooksPages)/sizeof(int);

Once you know the dimension of the array, you can use it as you see fit. For example, you can display it using a cout operator

cout << "Size of BooksPages = " << RecordSize << endl;

Or you can use it wherever the array is involved:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Initializing the whole array double
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };
    int ArraySize = sizeof(SquareRoot)/sizeof(double);

    cout << "Array Dimension = " << ArraySize << endl;

    // Displaying the values of members of the array
    cout << "Square Roots";
    for(int n = 0; n < ArraySize; n++)
        cout << "\nRoot " << n + 1 << " = " << SquareRoot[n];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Array Dimension = 5
Square Roots
Root 1 = 6.48
Root 2 = 8.306
Root 3 = 2.645
Root 4 = 20.149
Root 5 = 25.729

Press any key to continue...

Declaring Arrays

  1. Start Borland C++ Builder and create a project based on the Console Wizard where you will select the C++ radio button and the Console Application check box.
  2. Change the content of the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double Distances[5] = {120.45, 252.28, 610.18, 461.50, 813.22};
    
        cout << "Distances between cities\n";
        cout << "\nBaltimore - NY:    " << Distances[0]
             << "\nOrlando - Buffalo: " << Distances[1]
             << "\nQuebec - Ontario:  " << Distances[2]
             << "\nRockville - Miami: " << Distances[3]
             << "\nMiami - Houston:   " << Distances[4];
    
        cout << "\n\nPress any key to continue...";
        getchar();
        return 0;
    }
    //---------------------------------------------------------------------------
  3. To test the program, press F9:
     
    Distances between cities
    
    Baltimore - NY:    120.45
    Orlando - Buffalo: 252.28
    Quebec - Ontario:  610.18
    Rockville - Miami: 461.5
    Miami - Houston:   813.22
    
    Press any key to continue...
  4. Return to Bcb
  5. To define a constant integer as the dimension of the array, change the declaration of the array as:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        const int Items = 5;
        double Distances[Items] = {120.45, 252.28, 610.18, 461.50, 813.22};
    
        cout << "Distances between cities\n";
        cout << "\nBaltimore - NY:    " << Distances[0]
             << "\nOrlando - Buffalo: " << Distances[1]
             << "\nQuebec - Ontario:  " << Distances[2]
             << "\nRockville - Miami: " << Distances[3]
             << "\nMiami - Houston:   " << Distances[4];
    
        cout << "\n\nPress any key to continue...";
        getchar();
        return 0;
    }
    //---------------------------------------------------------------------------
  6. Press F9 to test the program and return to Bcb.

Operations on Arrays

A member of an array is a regular variable, like those we have learned so far. It can be initialized, requested, accessed, or processed. To perform an operation on a member of an array, use its position.

Algebraic Operations on Array Members

Once you have the members of an array, you can perform any of the mathematical operations we are familiar with.

float Value[5] = { 242.35, 120.05, 926.12, 47.28, 762.73 };

You can add the member values to each other using the addition operator:

Example 1:
float NewValue = Value[1] + Value[4];
      
cout << "\n";
Example 2:
cout << Value[1] << " + " << Value[4] << " = " << Value[1] + Value[4];

In the same way, you can calculate the sum of the members of an array:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Count;
    double MagazinePrice[] = {5.95, 3.65, 2.95, 10.45, 5.95};
    double Sum = 0.00;

    cout << "The price for each magazine is";
    for(Count = 0; Count < 5; Count++)
    {
        cout << "\nMagazine " << Count + 1 << ": $" << MagazinePrice[Count];
        Sum += MagazinePrice[Count];
    }
    cout << "\n\nThe total price is: $" << Sum;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The price for each magazine is
Magazine 1: $5.95
Magazine 2: $3.65
Magazine 3: $2.95
Magazine 4: $10.45
Magazine 5: $5.95

The total price is: $28.95

Press any key to continue...

You can subtract the values of the members of an array:

Example 1:
float NewValue = Value[0] - Value[2];
Example 2:
cout << Value[0] << " - " << Value[2] << " = " << Value[0] - Value[2];

You can multiply two member values:

Example 1:
float NewValue = Value[1] * Value[3];
Example 2:
cout << Value[1] << " * " << Value[3] << " = " << Value[1] * Value[3];

Or you can divide their values:

Example 1:
float NewValue = Value[2] / Value[3];
Example 2:
cout << Value[2] << " / " << Value[3] << " = " << Value[2] / Value[3];

An array can also be involved with a value external to the array. A value of an array member can be added to:

Distance[2] + 40.50;

It can be subtracted from:

StudentAge[25] – 12;

It can be multiplied:

Radius[4] * 5.14;

It can also be divided:

6250 / Salary[i];

Requesting Array Members

Just like you can request a variable's value from the user, you can also request an array member's value using the cin operator. Since each member is recognized by its position, specify it in your request. To display the value of the 1st member of an array of players, you would write:

cout << Players[0];

To request the value of the 3rd member of an array of players, use

cin >> Players[2];

Consequently, a program used to request 5 numbers from the user and display them would look as follows:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    short Number[5];

    cout << "Enter 5 numbers\n";
    cout << "Number 0: ";
    cin >> Number[0];
    cout << "Number 1: ";
    cin >> Number[1];
    cout << "Number 2: ";
    cin >> Number[2];
    cout << "Number 3: ";
    cin >> Number[3];
    cout << "Number 4: ";
    cin >> Number[4];

    cout << "\nThe numbers you entered were:";
    cout << "\nNumber 0: " << Number[0];
    cout << "\nNumber 1: " << Number[1];
    cout << "\nNumber 2: " << Number[2];
    cout << "\nNumber 3: " << Number[3];
    cout << "\nNumber 4: " << Number[4];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program: 

Enter 5 numbers
Number 0: 144
Number 1: 208
Number 2: 3206
Number 3: 8
Number 4: 64

The numbers you entered were:
Number 0: 144
Number 1: 208
Number 2: 3206
Number 3: 8
Number 4: 64

Press any key to continue...

Using the for loop, the previous program would be written as follows: 

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    short Number[5];

    cout << "Enter 5 numbers:\n";
    for( int i = 0; i < 5; ++i )
    {
        cout << "Number " << i << ": ";
        cin >> Number[i];
    }

    cout << "\nThe numbers you entered were:";
    for( int i = 0; i < 5; ++i )
        cout << "\nNumber " << Number[i];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program: 

Enter 5 numbers:
Number 0: 90
Number 1: 902
Number 2: 1944
Number 3: 75
Number 4: 6806

The numbers you entered were:
Number 90
Number 902
Number 1944
Number 75
Number 6806

Press any key to continue...

To request an array of floating point variables from the user, you would just change the declaration of the arrary as follows:

float Number[5];

The dimensions of the arrays we have used so far were set by the programmer. When writing your program, you might not know how many members would fill the array. Sometimes a dependent operation on the program would be performed to set the dimension of the array. You can also let the user determine the number of items. Since you must first define the dimension of the array, you can set a random number. If the number will be set by a previous operation of the program, you can guess the maximum dimension of the array. In the following program, the number would be set by the user.

You can request the value of each member using its position as we have seen already; but you should use a for loop to navigate through the list. This makes your program shorter and more professional:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int n;
    float Number[100];

    cout << "How many numbers do you want to enter? ";
    cin >> n;

    cout << "\nEnter " << n << " decimal numbers:\n";
    for( int i = 0; i < n; ++i )
    {
        cout << "Number " << i + 1 << ": ";
        cin >> Number[i];
    }

    cout << "\nThe numbers you entered were:";
    for( int i = 0; i < n; ++i )
        cout << "\nNumber " << Number[i];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

How many numbers do you want to enter? 6

Enter 6 decimal numbers:
Number 1: 28.44
Number 2: -1880.12
Number 3: -44.68
Number 4: -500.25
Number 5: 842.24
Number 6: -0.22

The numbers you entered were:
Number 28.44
Number -1880.12
Number -44.68
Number -500.25
Number 842.24
Number -0.22

Press any key to continue...

Arrays and Functions

Since it is a variable, an array can be passed to a function and a function can return an array. In order to use an array in your program, like any variable, you must first declare it. If the array is not initialized, you must specify its dimension. Here is an example:

int PagesPerBook[100];

To pass an array to a function, you do not need to specify the array’s dimension (although you are allowed to). When declaring and when defining the function, supply the array using its data type, its name and its square brackets. Here is an example:

void AddDistances(double d[]);

As we have learned with functions, when declaring a function, you do not need to specify the name of the array. The AddDistances() function could be declared as follows:

void AddDistances(double[]);

When defining the function, make sure you use a valild name for the array. Most of the time, when using an array on a function, the function would need to know the size of the array. Therefore, you will usually pass a second argument that specifies the dimension of the array. Here is an example:

void RequestPages(int d, int x[]);

This second argument helps the function process the array. You can then use it to initialize an array:

//---------------------------------------------------------------------------
void __fastcall RequestPages(int Count, int k[])
{
    cout << "Enter the number of pages for each book\n";
    for(int i = 0; i < Count; i++)
    {
        cout << "Book #" << i + 1 << ": ";
        cin >> k[i];
    }
}
//---------------------------------------------------------------------------

When calling the function, use only the name of the array, you should not need to specify the dimension of the array. Here is an example:

RequestPages(n, PagesPerBook);

As we will soon see when studying arrays and pointers, when you pass an array to a function, the array cannot be passed by value. When declaring an array, the name of the array is a pointer to the array. Therefore, when an array is passed to a function, the array is passed as a pointer. For this reason, any change made on the array is kept and passed back to the calling function. This allows you to perform operations of array members and modify their values. Here is our program passing arrays to functions:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int i, n;
    int PagesPerBook[100];
    int __fastcall RequestNbrOfBooks();
    void __fastcall RequestPages(int d, int x[]);
    void __fastcall ShowPages(int e, int y[]);

    n = RequestNbrOfBooks();
    RequestPages(n, PagesPerBook);

    cout << "\nReadership summary";
    cout << "\nThis year you read " << n << " books";

    ShowPages(n, PagesPerBook);

    cout << "\n\nPress any key to continue...";
    getchar();
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
int __fastcall RequestNbrOfBooks()
{
    int i;

    cout << "How many books have you read this year? ";
    cin >> i;

    return i;
}
//---------------------------------------------------------------------------
void __fastcall RequestPages(int Count, int k[])
{
    cout << "Enter the number of pages for each book\n";
    for(int i = 0; i < Count; i++)
    {
        cout << "Book #" << i + 1 << ": ";
        cin >> k[i];
    }
}
//---------------------------------------------------------------------------
void __fastcall ShowPages(int c, int s[])
{
    cout << "\nBook #\tNbr Of Pages";
    for(int i = 0; i < c; i++)
        cout << "\n " << i + 1 << "\t" << s[i];
}
//---------------------------------------------------------------------------

Here is an example of running the program:

How many books have you read this year? 5
Enter the number of pages for each book
Book #1: 244
Book #2: 882
Book #3: 79
Book #4: 325
Book #5: 504

Readership summary
This year you read 5 books
Book #  Nbr Of Pages
 1      244
 2      882
 3      79
 4      325
 5      504

Press any key to continue...

Multidimensional Arrays

The arrays we have used so far are referred to as a single-dimensional because all of their values can be written on the same row or a unique range. Imagine that you write a series of floating-point numbers on a piece of paper. You can use just one line of text to write these numbers. If the line gets filled, you would continue on the second line, and so forth.

If you are writing a program that would evaluate the number of floating-point numbers that are written on a piece of paper, each line could represent an array: a single dimensional array of floating-point numbers. The array could be declared as follows:

double Prices[] = {5.95, 3.65, 2.95, 10.45, 5.95};

This would be represented as follows:

5.95 3.65 2.95 10.45 5.95

As we have seen already, the members of a single dimensional array are recognized by their positions.

While a single-dimensional array is an array of variables, a multiple-dimensional array is an array of arrays. More complicated or advanced groups of items are also called arrays of arrays.

Two-Dimensional Arrays

When a one-dimension array is not sufficient to represent a variable, you can expand it by creating an array of two arrays. This is makes it double-dimensional. A two-dimensional array can be represented as a series of rows and columns. Each row would represent a single-dimensional array, which we represent horizontally. A column would represent the second dimension of the array. Expanding on the Prices array above, we can create a second series of prices as follows:

To represent a two-dimensional array, you use a double pair of square brackets, each pair representing one dimension. A double-dimensional array of double-precision numbers, made of three columns and two rows, such as above, can be declared with:

double Prices[2][5];

The first square bracket of a two-dimensional array represents the number of arrays. For example, the Prices array represents two groups of double-precision numbers. The second square bracket represnts the number of items that each array holds. In this case, each array (or each of of the two arrays) holds 5 numbers. Because the second square represents the dimension of each array, its number must also be an integer.

Initializing a Two-Dimensional Array

We learned earlier that a single-dimensional array can be initialized as follows:

double Prices[] = {5.95, 3.65, 2.95, 10.45, 5.95};

Since a two-dimensional array is in fact a group of two arrays, each array must be initialized in its own pair of curly brackets. And since each is part of the group of arrays, each will be enclosed between the main square brackets of the array variable. To initialize the Prices array above, you can write:

Each member of the array can be recognized by its position. For the Prices array, the positions and their values are:

Prices[0][0]=5.95 Prices[0][1]=3.65 Prices[0][2]=2.95  Prices[0][3]=10.45 Prices[0][4]=5.95
Prices[1][0]=12.15 Prices[1][1]=6.55 Prices[1][2]=8.95 Prices[1][3]=1.25 Prices[1][4]=1.65

With an array initialized as above, you can display the value of each member by referring to its position. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Prices[2][5] = {
                            { 5.95, 3.65, 2.95, 10.45, 5.95 },
                            { 12.15, 6.55, 8.95, 1.25, 1.65 }
                          };

    cout << "Array Representation";
    cout << "\nPosition[0][0]: " << Prices[0][0];
    cout << "\nPosition[0][1]: " << Prices[0][1];
    cout << "\nPosition[0][2]: " << Prices[0][2];
    cout << "\nPosition[0][3]: " << Prices[0][3];
    cout << "\nPosition[0][4]: " << Prices[0][4];
    cout << "\nPosition[1][0]: " << Prices[1][0];
    cout << "\nPosition[1][1]: " << Prices[1][1];
    cout << "\nPosition[1][2]: " << Prices[1][2];
    cout << "\nPosition[1][3]: " << Prices[1][3];
    cout << "\nPosition[1][4]: " << Prices[1][4];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Array Representation
Position[0][0]: 5.95
Position[0][1]: 3.65
Position[0][2]: 2.95
Position[0][3]: 10.45
Position[0][4]: 5.95
Position[1][0]: 12.15
Position[1][1]: 6.55
Position[1][2]: 8.95
Position[1][3]: 1.25
Position[1][4]: 1.65

Press any key to continue...

You can also initializing a two-dimensional array by listing all of its members in one row. Here is an example:

double Prices[2][5] =
{ 5.95, 3.65, 2.95, 10.45, 5.95, 12.15, 6.55, 8.95, 1.25, 1.65 };

Once again, the array members are known by their positions. For a 2x5 array declared as Prices[2][5], the incremental positions of the members are:

Prices[0][0], Prices[0][1], Prices[0][2], Prices[0][3], Prices[0][4], Prices[1][0], Prices[1][1], Prices[1][2], Prices[1][3], and Prices[1][4].

You can access each using its position. Alternatively, if you initialize a two-dimensional array as the one above, the compiler knows the value that resides at which position, and you can ask the compiler to access a member by referring to its position:

//---------------------------------------------------------------------------
/*#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int i, n;
    int PagesPerBook[100];
    int __fastcall RequestNbrOfBooks();
    void __fastcall RequestPages(int d, int x[]);
    void __fastcall ShowPages(int e, int y[]);

    n = RequestNbrOfBooks();
    RequestPages(n, PagesPerBook);

    cout << "\nReadership summary";
    cout << "\nThis year you read " << n << " books";

    ShowPages(n, PagesPerBook);

    cout << "\n\nPress any key to continue...";
    getchar();
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
int __fastcall RequestNbrOfBooks()
{
    int i;

    cout << "How many books have you read this year? ";
    cin >> i;

    return i;
}
//---------------------------------------------------------------------------
void __fastcall RequestPages(int Count, int k[])
{
    cout << "Enter the number of pages for each book\n";
    for(int i = 0; i < Count; i++)
    {
        cout << "Book #" << i + 1 << ": ";
        cin >> k[i];
    }
}
//---------------------------------------------------------------------------
void __fastcall ShowPages(int c, int s[])
{
    cout << "\nBook #\tNbr Of Pages";
    for(int i = 0; i < c; i++)
        cout << "\n " << i + 1 << "\t" << s[i];
}
//---------------------------------------------------------------------------
*/
//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Prices[2][5] =
        { 5.95, 3.65, 2.95, 10.45, 5.95, 12.15, 6.55, 8.95, 1.25, 1.65 };

    cout << "Array Representation";
    cout << "\nPosition[0][0]: " << Prices[0][0];
    cout << "\nPosition[0][1]: " << Prices[0][1];
    cout << "\nPosition[0][2]: " << Prices[0][2];
    cout << "\nPosition[0][3]: " << Prices[0][3];
    cout << "\nPosition[0][4]: " << Prices[0][4];
    cout << "\nPosition[1][0]: " << Prices[1][0];
    cout << "\nPosition[1][1]: " << Prices[1][1];
    cout << "\nPosition[1][2]: " << Prices[1][2];
    cout << "\nPosition[1][3]: " << Prices[1][3];
    cout << "\nPosition[1][4]: " << Prices[1][4];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

A two-dimensional array can be represented as a series of rows and columns as follows:

On an array defined as [2][5], the first dimension represents the rows and the second dimension represents the columns. Earlier, we saw that, using a for loop, you can access the value that resides in an array using the incremental position of the value. Because a one-dimensional array can be represented a series of columns, such a for loop would access each column of the array. On a two-dimensional array, you would need two for loops to access each member of the array. The first for loop invokes the first dimension of the array or the rows. The second for loop must be nested in the first for loop and is used to access each column. This can be illustrated as:

for Each Row
    for Each Column of the above row
        I will do my thing

Using for loops, the above program can be written as follows:

//---------------------------------------------------------------------------
/*#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int i, n;
    int PagesPerBook[100];
    int __fastcall RequestNbrOfBooks();
    void __fastcall RequestPages(int d, int x[]);
    void __fastcall ShowPages(int e, int y[]);

    n = RequestNbrOfBooks();
    RequestPages(n, PagesPerBook);

    cout << "\nReadership summary";
    cout << "\nThis year you read " << n << " books";

    ShowPages(n, PagesPerBook);

    cout << "\n\nPress any key to continue...";
    getchar();
    getchar();
    return 0;
}
//---------------------------------------------------------------------------
int __fastcall RequestNbrOfBooks()
{
    int i;

    cout << "How many books have you read this year? ";
    cin >> i;

    return i;
}
//---------------------------------------------------------------------------
void __fastcall RequestPages(int Count, int k[])
{
    cout << "Enter the number of pages for each book\n";
    for(int i = 0; i < Count; i++)
    {
        cout << "Book #" << i + 1 << ": ";
        cin >> k[i];
    }
}
//---------------------------------------------------------------------------
void __fastcall ShowPages(int c, int s[])
{
    cout << "\nBook #\tNbr Of Pages";
    for(int i = 0; i < c; i++)
        cout << "\n " << i + 1 << "\t" << s[i];
}
//---------------------------------------------------------------------------
*/
//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Prices[2][5] =
        { 5.95, 3.65, 2.95, 10.45, 5.95, 12.15, 6.55, 8.95, 1.25, 1.65 };

    cout << "Array Representation";
    for(int i = 0; i < 2; i++)
        for(int j = 0; j < 5; j++)
            cout << "\nPosition[" << i << "][" << j << "]: " << Prices[i][j];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Multidimensional Arrays

A two-dimensional array can be represented like a month of a calendar:

  Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Week 1 1 2 3 4 5 6 7
Week 2 8 9 10 11 12 13 14
Week 3 15 16 17 18 19 20 21
Week 4 22 23 24 25 26 27 28

A three-dimensional array adds a third level and can be thought of as each month of a year. While a two-dimensional array can be visualized as a table made of rows with each row made of columns, a three-dimensional array can be thought of a group of tables with each table made of rows and each row made of columns. Such an array can be declared as follows:

int Day[12][4][7];

This array is made of 12 tables. Each table contains 4 rows. Each row contains 7 columns.

To access each member of a multi-dimensional array, use its position. For example, on a three-dimensional array of [5][8][2], if the array is initialized in one series, the first item is at position [0][0][0], the 3rd item is at [0][0][2], etc.

Here is an example of a three dimension array:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // An accounting company processes payrolls different small businesses
    // This array represents two companies,
    //      each company is represented by 4 employees
    //      each employee is represented by the number of hours he or she
    //          worked for the 7-day week
    double EmployeeHours[2][4][7] =
    {
        {
            { 8.50, 7.00, 7.50, 8.00, 8.50, 0.00,  0.00 },
            { 8.00, 8.50, 0.00, 0.00, 8.00, 10.00, 8.50 },
            { 0.00, 0.00, 0.00, 0.00, 8.00, 9.00,  8.00 },
            { 9.00, 9.00, 8.00, 8.50, 8.00, 0.00,  0.00 },
        },
        {
            { 6.00, 7.50, 5.50, 7.00, 7.50, 0.00,    0.00 },
            { 10.50, 9.50, 10.00, 10.50, 0.00, 0.00, 0.50 },
            { 8.00, 8.00, 8.00, 8.00, 8.00, 0.00,    0.00 },
            { 9.00, 9.00, 6.00, 6.50, 8.00, 0.00,    0.00 }
        }
    };

    cout << "Array Representation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    for(int i = 0; i < 2; i++)
        for(int j = 0; j < 4; j++)
            for(int k = 0; k < 7; k++)
                cout << "\nHours[" << i << "][" << j << "][" << k << "]: "
                     << EmployeeHours[i][j][k];

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Array Representation
Hours[0][0][0]: 8.50
Hours[0][0][1]: 7.00
Hours[0][0][2]: 7.50
Hours[0][0][3]: 8.00
Hours[0][0][4]: 8.50
Hours[0][0][5]: 0.00
Hours[0][0][6]: 0.00
Hours[0][1][0]: 8.00
Hours[0][1][1]: 8.50
Hours[0][1][2]: 0.00
Hours[0][1][3]: 0.00
Hours[0][1][4]: 8.00
Hours[0][1][5]: 10.00
Hours[0][1][6]: 8.50
Hours[0][2][0]: 0.00
Hours[0][2][1]: 0.00
Hours[0][2][2]: 0.00
Hours[0][2][3]: 0.00
Hours[0][2][4]: 8.00
Hours[0][2][5]: 9.00
Hours[0][2][6]: 8.00
Hours[0][3][0]: 9.00
Hours[0][3][1]: 9.00
Hours[0][3][2]: 8.00
Hours[0][3][3]: 8.50
Hours[0][3][4]: 8.00
Hours[0][3][5]: 0.00
Hours[0][3][6]: 0.00
Hours[1][0][0]: 6.00
Hours[1][0][1]: 7.50
Hours[1][0][2]: 5.50
Hours[1][0][3]: 7.00
Hours[1][0][4]: 7.50
Hours[1][0][5]: 0.00
Hours[1][0][6]: 0.00
Hours[1][1][0]: 10.50
Hours[1][1][1]: 9.50
Hours[1][1][2]: 10.00
Hours[1][1][3]: 10.50
Hours[1][1][4]: 0.00
Hours[1][1][5]: 0.00
Hours[1][1][6]: 0.50
Hours[1][2][0]: 8.00
Hours[1][2][1]: 8.00
Hours[1][2][2]: 8.00
Hours[1][2][3]: 8.00
Hours[1][2][4]: 8.00
Hours[1][2][5]: 0.00
Hours[1][2][6]: 0.00
Hours[1][3][0]: 9.00
Hours[1][3][1]: 9.00
Hours[1][3][2]: 6.00
Hours[1][3][3]: 6.50
Hours[1][3][4]: 8.00
Hours[1][3][5]: 0.00
Hours[1][3][6]: 0.00

Press any key to continue...

When it comes to multi-dimensional arrays, one of the issues you will be confronted with is the size of the array. This can be calculated by using the sizeof operator as follows:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <iomanip.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // An accounting company processes payrolls different small businesses
    // This array represents two companies,
    //      each company is represented by 4 employees
    //      each employee is represented by the number of hours he or she
    //          worked for the 7-day week
    double EmployeeHours[2][4][7] =
    {
        . . .
    };

    cout << "Array Representation";
    cout << setiosflags(ios::fixed) << setprecision(2);
    for(int i = 0; i < 2; i++)
        for(int j = 0; j < 4; j++)
            for(int k = 0; k < 7; k++)
                cout << "\nHours[" << i << "][" << j << "][" << k << "]: "
                     << EmployeeHours[i][j][k];

    int Size = sizeof(EmployeeHours) / sizeof(double);
    cout << "\n\nThe EmployeesHours array occupies " << Size << " bytes";

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The EmployeesHours array occupies 56 bytes

Press any key to continue...

Arrays of Characters

Consider a name such as James; this is made of 5 letters, namely J, a, m, e, and s. Such letters, called characters, can be created and initialized as follows:

char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:

cout << "The name is " << L1 << L2 << L3 << L4 << L5;

Here is such a program: 

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

    cout << "The name is " << L1 << L2 << L3 << L4 << L5;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The name is James
Press any key to continue...

 

char ArrayName[Dimension];
char CountryName[Dimension];
char CountryName[32];
char Country[50];

We have used characters in the past for variables such as names. The arrays of characters deserve a special study because they are the basis for strings. Any word you write is an array of charaters. What sets arrays of charaters apart is that they mostly lead to two-dimensional arrays.

Declaring and Initializing an Array of Characters

From our study and use of characters, we have seen that, to declare a character variable, we can use any C++ valid name. To initialize a character variable, type it between single-quotes. Here is an example:

char Answer = ‘y’;

To declare an array of characters, type the char keyword followed by the techniques we used to declare the other arrays. The syntax is:

char ArrayName[Dimension];

The char keyword and the square brackets let the compiler know that you are declaring an array of characters. The name of the array follows the same rules and suggestions we have used for the other variables. Once again, the dimension of the array could be an approximation of the number of characters you anticipate.

To initialize an array of characters, you use the curly brackets. This time, each character would be enclosed in single-quotes. If you know the characters you will be using to initialize the array, you should omit specifying the dimension. Here is an example:

char Color[] = { 'B', 'l', 'a', 'c', 'k' };

Another technique used to initialize an array of characters is to type the array between double-quotes. Since you know the array, let the compiler figure out its dimension. Here is an example:

char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator. The compiler already knows the dimension and the content of the array:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    char Color[] = { 'B', 'l', 'a', 'c', 'k' };
    char Country[] = "Swaziland";

    cout << "Color = " << Color << endl;
    cout << "Country = " << Country;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Color = BlackCountry = Swaziland
Press any key to continue...

Creating an Array of Characters

  1. Create a new C++ Console Application without saving the previous project.
  2. Change the content of the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        char FName[] = "Jules";
        char MI = 'B';
        char LName[] = "Moon";
        float WeeklyHours[] = { 8.00, 6.50, 7.25, 8.00, 9.50 };
        float SumHours = 0;
        float Salary = 8.12;
    
        cout << "Employee's Name: " << FName << " " << MI << ". " << LName;
        cout << "\nTotal weekly hours: ";
    
        for( int i = 0; i < 5; ++i )
        SumHours += WeeklyHours[i];
    
        cout << SumHours;
        cout << "\nWeekly Earnings = $" << SumHours * Salary;
    
        cout << "\n\nPress any key to continue...";
        getchar();
        return 0;
    }
    //---------------------------------------------------------------------------
  3. To test the program, press F9:
     
    Employee's Name: Jules B. Moon
    Total weekly hours: 39.25
    Weekly Earnings = $318.71
    
    Press any key to continue...
  4. Return to Bcb

Requesting an Array of Characters

Instead of initializing an array, sometimes you will have to wait until the program is running, to assign a value to the array. First, you must declare the array, specifying an approximate dimension. To request the value of an array of characters, use the cin operator, specifying only the name of the array. Here is an example:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    char FirstName[20];
    char MI;
    char LastName[20];

    cout << "The following pieces of information are need"
         << "to complete your application\n";
    cout << "First Name: ";
    cin >> FirstName;
    cout << "Middle Initial: ";
    cin >> MI;
    cout << "Last Name: ";
    cin >> LastName;
    cout << "\nMember Information";
    cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

The following pieces of information are need
to complete your application

First Name: Michael
Middle Initial: J
Last Name: Callhoun

Member Information
Full Name: Michael J. Callhoun

Press any key to continue...

If you use the “normal” cin operator above, the compiler expects the user to type a one-word string from the keyboard. If you want the user to type text that includes space, you should use the cin::getline() function. The syntax of the getline() function is:

cin.getline(ArrayName, Dimension, Delimiter=’\n’);

The array name is the one you used when declaring the array. The dimension is the same value you set when declaring the variable. The delimiter is an optional character that the user would type to specify the end of the string. By default, the compiler expects the user to press Enter to end the string. Logically, the following program illustrates the use of the cin::getline() function to request text strings from the user:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    char Author[40];
    char Title[40];
    char Publisher[50];

    cout << "Book Collection\n";
    cout << "Author: ";
    cin.getline(Author, 40);
    cout << "Title: ";
    cin.getline(Title, 40);
    cout << "Publisher: ";
    cin.getline(Publisher, 50);
    cout << "\nBook Information";
    cout << "\nAuthor Name: " << Author
         << "\nBook Title: " << Title
         << "\nPublisher: " << Publisher;

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

The implementation of this function under C++ Builder obliges the user to press Enter to end a string.. Here is an example of running the program:

ook Collection
Author: Elliot Mendelson
Title: 3000 Solved Problems In Calculus
Publisher: McGraw Hill

Book Information
Author Name: Elliot Mendelson
Book Title: 3000 Solved Problems In Calculus
Publisher: McGraw Hill

Press any key to continue...

There are two alternatives to solve this problem: you can use the getline() function from the basic_string library or you can use the gets() function from the C language.

Arrays and Classes

We have learned to treat objects as variables including creating an object by declaring variables. We can define an object as follows:

//---------------------------------------------------------------------------

#ifndef RentDateH
#define RentDateH
//---------------------------------------------------------------------------
class TRentDate
{
public:
    __fastcall TRentDate();
    __fastcall TRentDate(int m, int d, int y);
    __fastcall TRentDate(const TRentDate& D);
    __fastcall ~TRentDate();
    void __fastcall setMonth(int m) { Month = m; }
    void __fastcall setDay(int d) { Day = d; }
    void __fastcall setYear(int y) { Year = y; }
    void __fastcall setDate(int m, int d, int y);
    int __fastcall getMonth() const { return Month; }
    int __fastcall getDay() const { return Day; }
    int __fastcall getYear() const { return Year; }
private:
    int Month;
    int Day;
    int Year;
};
//---------------------------------------------------------------------------
#endif

We also learned to implement such an object as follows:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop

#include "RentDate.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
__fastcall TRentDate::TRentDate()
    : Month(1), Day(1), Year(1990)
{
}
//---------------------------------------------------------------------------
__fastcall TRentDate::TRentDate(int m, int d, int y)
    : Month(m), Day(d), Year(y)
{
}
//---------------------------------------------------------------------------
__fastcall TRentDate::TRentDate(const TRentDate& RD)
    : Month(RD.Month), Day(RD.Day), Year(RD.Year)
{
}
//---------------------------------------------------------------------------
__fastcall TRentDate::~TRentDate()
{
}
//---------------------------------------------------------------------------
void __fastcall TRentDate::setDate(int m, int d, int y)
{
    setMonth(m);
    setDay(d);
    setYear(y);
}
//---------------------------------------------------------------------------

Once we could define and implement such an object, we could test it using the main() function:

//---------------------------------------------------------------------------
#include <iostream.h>
#pragma hdrstop
#include "RentDate.h"
//---------------------------------------------------------------------------

#pragma argsused
//---------------------------------------------------------------------------
void __fastcall RequestDate(TRentDate& D)
{
    int m, d, y;

    cout << "Month: ";
    cin >> m;
    cout << "Day: ";
    cin >> d;
    cout << "Year: ";
    cin >> y;

    D.setDate(m, d, y);
}
//---------------------------------------------------------------------------
void __fastcall ShowDate(const TRentDate& D)
{
    cout << "Rent date: " << D.getMonth()
         << "/" << D.getDay() << "/" << D.getYear();
}
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    TRentDate Renter;

    RequestDate(Renter);
    cout << endl;
    ShowDate(Renter);

    cout << "\n\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Month: 10
Day: 24
Year: 1988

Rent date: 10/24/1988

Press any key to continue...

Just like we would declare an array of variables, we can declare an array of objects and manipulate each member of the array as if it were a regular variable.

Declaring Member Arrays

Many of the member variables of objects used in C++ are made of strings. For example, to create a person object, you would need variables such as first name, address, etc. These variables can be declared as arrays of characters. To declare an array of characters as a member of an object, use the same syntax you would if you were declaring an array in a function. Here are examples:

//---------------------------------------------------------------------------
#ifndef CustomerH
#define CustomerH
//---------------------------------------------------------------------------
class TCustomer
{
public:
    __fastcall TCustomer();
    __fastcall ~TCustomer();
    void __fastcall RequestTheName();
    void __fastcall RequestTheAddress();
    void __fastcall DisplayName();
    void __fastcall DisplayAddress();
private:
    char FirstName[20];
    char LastName[20];
    char Address[50];
    char City[20];
    char State[3];
    long ZIPCode;
};
//---------------------------------------------------------------------------
#endif

To request the values of these strings, we saw earlier that we cannot use the “normal” getline() function. Instead, we would use the gets() function of the C language. The gets() function takes one argument which is the string that is being requested from the user. Here is the implementation of the TCustomer object with the gets() functions requesting strings from the user:

//---------------------------------------------------------------------------
#include <iostream.h>
#include <stdio.h>
#pragma hdrstop
#include "Customer.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
__fastcall TCustomer::TCustomer()
{
}
//---------------------------------------------------------------------------
__fastcall TCustomer::~TCustomer()
{
    //TODO: Add your source code here
}
//---------------------------------------------------------------------------
void __fastcall TCustomer::RequestTheName()
{
    // You have to/must use C here.
    // Raw C++ would not allow the next function
    printf("First Name: ");
    gets(FirstName);
    printf("Last Name: ");
    gets(LastName);
}
//---------------------------------------------------------------------------
void __fastcall TCustomer::RequestTheAddress()
{
    printf("Type the full address\n");
    printf("Street: ");
    gets(Address);
    printf("City: ");
    gets(City);
    cout << "State: ";
    cin >> State;
    cout << "ZIP Code: ";
    cin >> ZIPCode;
}
//---------------------------------------------------------------------------
void __fastcall TCustomer::DisplayName()
{
    cout << "\nFull Name: " << FirstName << " " << LastName;
}
//---------------------------------------------------------------------------
void __fastcall TCustomer::DisplayAddress()
{
    cout << "\nAddress: " << Address;
    cout << "\nCity: " << City << ", " << State << " " << ZIPCode;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

First Name: Jeannette
Last Name: Carlton
Type the full address
Street: 912 Leandro Rd #D12
City: Alexandria
State: VA
ZIP Code: 22231

Customer Information
Full Name: Jeannette Carlton
Address: 912 Leandro Rd #D12
City: Alexandria, VA 22231

Press any key continue...

Processing an Array of Objects

As a (programmer defined) data type, an object can be involved in all aspects of an array. We have just learned how member variables of an object can be arrays. To use an array of objects in a program, declare the array like any other. This means that you will specify the name of the object, the name of the instance and an estimate dimension of the array.

Imagine you create an array of cars as follows:

//---------------------------------------------------------------------------
struct TCar
{
    int Color;
    int SeatCoverMaterial;
    double Price;
    bool CDPlayer;
};
//---------------------------------------------------------------------------

If you want to declare an array of 24 cars that are parked on the mall, you would declare such an array as follows:

TCar Parked[24]; // This is an array of 24 cars

Since an object itself is made of variables, you can access a particular variable of an object using the object’s instance position. The dimension of the array belongs to the object and not to its members. Therefore, the member access operator, the period “.”, would be typed after the square brackets that identify an instance of the object as an array. For example, to access the price of the 4th car, you would type:

Parked[5].Price;
 
 

Previous Copyright © 2002-2003 FunctionX, Inc. Next