Home

Introduction to Arrays

Fundamentals of Arrays

 

Introduction

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.

Practical Learning: Introducing 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>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  3. Save the application in a new folder named Arrays1
  4. Save the unit as Main.cpp and save the project as Arrays

Introduction to Arrays

An array is a data type used to create a group of values 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:

An array of people An array of buildings
An array of letters 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 an object as we will learn (structures, unions, and classes) 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 values 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. 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 a list of positive numbers, we could write:

unsigned int MembershipCategory[3];

In this case, all of the items of the MembershipCategory array must be valid positive numbers. 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.

Just as done with regular variables, you can declare various arrays in your program as we did above. If you want to declare two or more arrays of the same kind, you can declare them on the same line, separating them with a comma. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
int main(int argc, char* argv[])
{
    int HandballPlayers[6];
    double HourlySalary[5], WeeklySalary[5];
    unsigned BookCategory[10], MusicCategory[8], Videos[12];

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

Practical Learning: Declaring Arrays

  1. Declare an array as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        long Distance[6];
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Save the project

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 prices of 5 books in a book store can be declared as follows:

long double BookPrice[5];

In this case, the array is made of 5 members. This means that each member of the array has to be a double-precision number, a currency value. These members have their own values. The first one could have a value of 29.95. The second could be 49.55, etc. In the same way, 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 position is also referred to as an index. The members of an array are arranged starting at index 0, followed by index 1, then index 2, etc. This system of counting is referred to as "zero-based" because the counting starts at 0. The first item, at index 0, is identified as HandballPlayers[0] = 22; the second item, at index 1, is HandballPlayers [1] = 5.

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;

Notice that the value assigned to each array member is not directly related to the value of the index. That is, the square root of 0 is not 6.480, but 6.480 represents the first square root value, whatever the number referred to is. 

The advantage of initializing the members individually is that you do not have to follow their order, as long as you specify their index. 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;

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 curly bracket '}'. 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};
 

Practical Learning Practical Learning: Initializing an Array

  1. Initialize the array as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        long Distance[6] = { 322, 257, 1677, 713, 661, 91 };
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. To test the program, press F9:

Processing an Array

You can use the cout extractor to display the value of a member of an array. As we have learned, you can use each member’s index to display its value. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    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 index:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    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...

Since an array is a list of items, you can scan the array using a for loop. This allows you to perform a common operation on each member of the array. To do this, you can use a for loop that starts with the first index of the array and continues to the last item, visiting each member. Since an array is zero-based, to scan all members of the array, the count would start at 0 and would end at index-1. The syntax you would use is:

for(Counter = 0; Counter < (Index - 1); Increment)
    Process the array;

Since the subtraction operation has a higher precedence than the less than comparison (check Appendix A), you can omit the parentheses on the Index - 1 operation above:

for(Counter = 0; Counter < Index - 1; Increment)
    Process the array;

To scan the members of the array and display the value of each on a cout extractor, the above code could have been written:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

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

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

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 index. When you finish, the compiler would figure out the number of members 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>
#include <conio>
using namespace std;
#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...";
    getch();
    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>
#include <conio>
using namespace std;
#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...";
    getch();
    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, suppose 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 extractor:

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

Or you can use it wherever the array is involved:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    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...
 

Practical Learning Practical Learning: Declaring Arrays

  1. To display the values of the members of the array, change the main() function as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        long Distance[] = { 322, 257, 1677, 713, 661, 91 };
    
        cout << "Distances between cities\n";
        cout << "\nBaltimore  - NY City:   " << Distance[0] << " km"
             << "\nQuebec     - Montreal:  " << Distance[1] << " km"
             << "\nBombay     - calcutta:  " << Distance[2] << " km"
             << "\nMelbourne  - Sydney:    " << Distance[3] << " km"
             << "\nParis      - Marseille: " << Distance[4] << " km"
             << "\nCasablanca - Rabat:     " << Distance[5] << " km\n";
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program. This would produce:
     
    Distances between cities
    
    Baltimore  - NY City:   322 km
    Quebec     - Montreal:  257 km
    Bombay     - calcutta:  1677 km
    Melbourne  - Sydney:    713 km
    Paris      - Marseille: 661 km
    Casablanca - Rabat:     91 km
    
    Press any key to continue...
  3. Return to Bcb and save the project

Type Defining an Array

If you happen to create various arrays of the same kind, you can use the typedef keyword to create a custom name for similar arrays. The syntax used is:

typedef DataType ArrayName[Dimension];

The typedef keyword is required

DataType must be a known (int, char, double, etc) or an already defined data type (such as a class as will learn in subsequent lessons)

ArrayName is a regular name for a variable

The dimension of the variables is enclosed between square brackets.

An example of such a programmer defined data type is:

typedef int Player[11];

After this statement, the name Player by itself represents an array of 11 integers. Therefore, the word Player can be used to declare an array of 11 items. Here are examples:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
int main(int argc, char* argv[])
{
    typedef string Players[11];
    typedef unsigned int Categories[6];
    typedef double Salaries[5];

    // Each team is an array of 11 members of type Player
    Players Arsenal, Juventus, DCUnited, Canon;
    // Each variable here is an array of 6 positive integers of type Category
    Salaries HourlySalary, WeeklySalary;
    // Each category is a list of 5 double-precision numbers
    Categories BookCategory, MusicCategory, Videos;

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

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 index.

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];
  • You can calculate the sum of the members of an array:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #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...";
        getch();
        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];

One of the most regular operations you can perform on the members of an array is to add their values and get their sum. This can be taken care of by simply accessing each member's value by its index and adding them. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
int main(int argc, char* argv[])
{
    double Number[] = { 1874.52, -384.05, -46.12, 80.88, 627.14 };
    double Sum = 0;

    Sum = Number[0] + Number[1] + Number[2] + Number[3] + Number[4];

    cout << "Sum of the array members: " << Sum << endl;

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

You can also use a for loop to navigate through the members of the array and add each to the sum:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
int main(int argc, char* argv[])
{
    double Number[] = { 1874.52, -384.05, -46.12, 80.88, 627.14 };
    int Count = sizeof(Number) / sizeof(double);
    double Sum = 0;

    for(int i = 0; i < Count; i++)
        Sum += Number[i];

    cout << "Sum of the array members: " << Sum << endl;

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

This would produce:

Sum of the array members: 2151
Press any key to continue...

This same approach can help you find the mean value of the members of an array. This can be done by dividing the sum by the number of members of the array, which is the last index-1:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
int main(int argc, char* argv[])
{
    double Number[] = { 1874.52, -384.05, -46.12, 80.88, 627.14 };
    int Count = sizeof(Number) / sizeof(double);
    double Sum, Mean;

    for(int i = 0; i < Count; i++)
        Sum += Number[i];
    Mean = Sum / Count;

    cout << "Sum of the array members: " << Sum << endl;
    cout << "Mean value of the array:  " << Mean << endl;

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

This would produce:

Sum of the array members: 2152.37
Mean value of the array:  430.474

Press any key to continue...

Other types of operations you can perform on an array consists of comparing the values of its members to the values of another array members, either from the same array or from another array. You can also compare the value of an array member to an external constant. The point is that the member of an array is a constant value that can be independently accessed and used as any other value.

Practical Learning Practical Learning: Operating on Arrays

  1. Create a new C++ project using the Console Wizard.
  2. To save the project, create a new folder called Aerobics1
  3. Save the unit as Main.cpp and save the project as Aerobic
  4. In the unit, type the following:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        int Position;
        int Exercise[] = { 1, 2, 3 };
    
        cout << "Specify your position:\n"
             << "1 - Sitting Down\n"
             << "2 - Standing Up\n"
             << "3 - Laying Down\n";
        cout << "Your choice: ";
        cin >> Position;
        cout << endl;
    
        if( Position == Exercise[0] )
        {
            cout << "Good, we will start with the sitting exercise\n";
        	cout << "Now, align your back as vertically as you can.\n";
        }
        else if( Position == Exercise[1] )
        {
            cout << "OK, we will perform some standing exercises\n";
            cout << "Please lift your right knee as high as you can "
                 << "and keep it up for 5 seconds\n";
        }
        else if( Position == Exercise[2] )
        {
            cout << "Wonderful, let's start with laying down\n";
            cout << "Lay your back on the floor as horizontally as you can\n";
            cout << "Also lay the palm of both your hand as flat as possible "
                 << "on the floor\n";
        }
    
        cout << "\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Test the application. Here is an example:
     
    Specify your position:
    1 - Sitting Down
    2 - Standing Up
    3 - Laying Down
    Your choice: 2
    
    OK, we will perform some standing exercises
    Please lift your right knee as high as you can and keep it up for 5 seconds
    
    Press any key to continue...
  6. Return to Bcb

Requesting the Values of an Array

Just like you can request a variable's value from the user, you can also request an array member's value using the cin extractor. Since each member is recognized by its index, specify it in your request.  To request the value of the 3rd member of an array of players, you would type:

cin >> Players[2];

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

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#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...";
    getch();
    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>
#include <conio>
using namespace std;
#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...";
    getch();
    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 array 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 may not know the number of members that 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. You can request the value of each member using its index 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>
#include <conio>
using namespace std;
#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...";
    getch();
    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

An array can be passed to a function as argument. An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Member[5]);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[5])
{
    for(int i = 0; i < 5; i++)
        cout << "\nRoot " << i + 1 << " = " << Member[i];
    cout << endl;
}
//---------------------------------------------------------------------------

You do not have to specify the dimension of the array. This means that you can leave the square brackets empty:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Member[]);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[])
{
	for(int i = 0; i < 5; ++i)
		cout << "\nRoot" << i + 1 << ": " << Member[i];
	cout << endl;
}
//---------------------------------------------------------------------------

We have already seen that when you declare an array, the compiler reserves an amount of memory space for the members of the array. To locate these members, the compiler aligns them in a consecutive manner. For example (hypothetically), if a member is located at 1804 Lockwood drive, the next member would be located at 1805 Lockwood Drive. This allows the compiler not only to know where the members of a particular array are stored, but also in what block (like the block houses of a city) the array starts. This means that, when you ask the compiler to locate a member of an array, the compiler starts where the array starts and moves on subsequently until it finds the member you specified. If the compiler reaches the end of the block but doesn't find the member you specified, it stops, instead of looking for it all over the computer memory.

Based on this, when you call a function that has an array as argument, the compiler only needs the name of the array to process it. Therefore, the above function can be called as follows:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Member[]);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };

    // Displaying the values of members of the array
    cout << "Square Roots";
	DisplayTheArray(SquareRoot);

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[])
{
    for(int i = 0; i < 5; i++)
        cout << "\nRoot " << i + 1 << " = " << Member[i];

	cout << endl;
}
//---------------------------------------------------------------------------

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

Press any key to continue...

The good scenario we have used so far is that we know the number of members of our array and we can directly use it in the function that is passed the argument. Imagine that we want the function to know how many members the array has and we want to let the function know while we are calling it, after all, in some circumstances, we will not always know how many members we want the function to process. This should easily be done as follows:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Member[]);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };

    // Displaying the values of members of the array
    cout << "Square Roots";
    DisplayTheArray(SquareRoot[3]);

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[])
{
    for(int i = 0; i < 5; i++)
        cout << "\nRoot " << i + 1 << " = " << Member[i];

    cout << endl;
}
//---------------------------------------------------------------------------

Unfortunately, this program will not compile. Remember, we saw that the compiler wants only the name of the array, because the name by itself represents the whole array. SquareRoot[3] is a specific value of a member of the array, it is not a group of values. In other words, SquareRoot[3] is the same as 2.645. It is as if we want to pass 2.645 as the value to be treated and not as a subsequent group of values, because that is what an array is. Therefore, the compiler complains that you are passing a value after you have specifically stated that the argument would be a group of values and not a single value.

When you declare and define a function that takes an array as argument, if you plan to process the array, for example, if you want the calling function to control the number of elements to be processed, you should/must pass another argument that will allow the function to know the number of members of the array would be considered. Such a function can be declared and defined as follows:

void __fastcall DisplayTheArray(double Mbr[], int Size);

This time, when calling the function, you can specify the number of items that you want to process. This is done by providing a constant value of the other argument when calling the function. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Mbr[], int Size);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729 };

    // Displaying the values of members of the array
    cout << "Square Roots";
    DisplayTheArray(SquareRoot, 3);
    cout << endl;

    // Processing all members of the array
    int SizeOfArray = sizeof(SquareRoot)/sizeof(double);
    cout << "Square Roots";
    DisplayTheArray(SquareRoot, SizeOfArray);

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[], int Count)
{
    for(int i = 0; i < Count; i++)
        cout << "\nRoot " << i + 1 << " = " << Member[i];

    cout << endl;
}
//---------------------------------------------------------------------------

This would produce:

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

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...

Using this same concept of passing accompanying arguments, you can control how the called function would process the array. For example, you can specify the starting and end point to the processing of the array. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayTheArray(double Mbr[], int First, int Last);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double SquareRoot[] = { 6.480, 8.306, 2.645, 20.149, 25.729,
                            44.14, 720.52, 96.08, 468.78, 6.28 };
    // Displaying the values of members of the array
    cout << "Square Roots - From 3rd to 7th items";
    DisplayTheArray(SquareRoot, 2, 6);
    cout << endl;

    // Processing all members of the array
    int SizeOfArray = sizeof(SquareRoot)/sizeof(double);
    cout << "Square Roots - All items";
    DisplayTheArray(SquareRoot, 0, SizeOfArray);

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayTheArray(double Member[], int Start, int End)
{
    for(int i = Start; i < End; i++)
        cout << "\nRoot " << i + 1 << " = " << Member[i];

    cout << endl;
}
//---------------------------------------------------------------------------

This would produce:

Square Roots - From 3rd to 7th items
Root 3 = 2.645
Root 4 = 20.149
Root 5 = 25.729
Root 6 = 44.14

Square Roots - All items
Root 1 = 6.48
Root 2 = 8.306
Root 3 = 2.645
Root 4 = 20.149
Root 5 = 25.729
Root 6 = 44.14
Root 7 = 720.52
Root 8 = 96.08
Root 9 = 468.78
Root 10 = 6.28

Press any key to continue...

When declaring a function that takes an array argument, as we learned with other arguments, you don't have to provide a name of the argument. Simply typing the square brackets on the right side of the data type in the parentheses is enough. The name of the argument is only necessary when defining the function. Therefore, the above function can be declared as follows:

void __fastcall DisplayTheArray(double[], int, int);
Author Note The Visual Component Library provides a tremendous library of functions destined to perform various types of operations on arrays.
 

Multidimensional Arrays

 

Introduction

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 represents 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>
#include <conio>
using namespace std;
#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...";
    getch();
    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>
#include <conio>
using namespace std;
#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...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

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>
#include <conio>
using namespace std;
#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...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Two-Dimensional Arrays and Functions

To declare a function that takes a two-dimensional array as argument,, the name of the array must be followed by two pairs of square brackets. The first pair is empty, which means the compiler would find out the number of rows of the array. The second pair of square brackets must contain the number of columns of the array. If you plan to process the array, such as navigating through the members of the array, you should also pass two arguments representing the number of rows and the number of columns. Here is an example of such a declaration:

void __fastcall DisplayNumbers(int Nbr[][6], int Rows, int Cols);

When calling such a function, provide the name of the array and the other arguments, if any:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

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

#pragma argsused
void __fastcall DisplayNumbers(int Nbr[][6], int Rows, int Cols);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int Number[2][6] = { { 31, 28, 31, 30, 31, 30 },
                         { 31, 31, 30, 31, 30, 31 } };

    cout << "List of Numbers";
    DisplayNumbers(Number, 2, 6);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall DisplayNumbers(int Nbr[][6], int Rows, int Columns)
{
    for(int i = 0; i < Rows; i++)
        for(int j = 0; j < Columns; j++)
            cout << "\nNumber [" << i << "][" << j << "]: " << Nbr[i][j];
}
//---------------------------------------------------------------------------

 

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>
#include <conio>
using namespace std;
#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";
    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...";
    getch();
    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>
#include <conio>
using namespace std;
#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";
    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...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The EmployeesHours array occupies 56 bytes

Press any key to continue...

 

 

Previous Copyright © 2005 FunctionX, Inc. Next