Introduction to Arrays

A Series of Similar Items

Introduction to Lists

A list is a group of items. Normally, the items should be of the same type such as a group of people, a group of houses, a group of countries, etc. There are various ways you can programmatically create and manage a list.

Introduction to Arrays

So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:

int main()
{
    double number1 = 12.44;
    double number2 = 525.38;
    double number3 = 6.28;
    double number4 = 2448.32;
    double number5 = 632.04;
}

Instead of using individual variables that share the same characteristics, you can group the values in one entity and use that entity as one unit or a regular variable. This group is called an array. Therefore, an array is a group of items with the following characteristics:

Practical LearningPractical Learning: Introducing Arrays

  1. Start Microsoft Visual Studio
  2. Create a new C++ Console App named CountriesStatistics1

Array Creation

To create an array, you must specify the data type of its items. Each item of the array will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of each item of the array, you must use a common name to identify the group. The name of the artray is the name for the variable that all items of the array will use. The name of an array follows the rules of names of variables. In our lessons, since we consider that an array is a group of values, we will name our array variables in plural.

An Array Variable

Declaring an Array Variable

Unlike a regular list that can contain any number of items, an array has a fixed or constant number of items. Therefore, you must specify the number of items that will constitute the array. The number of items of an array is included in square brackets, as in [5]. Based on these rule, the primary formula to create an array is:

data-type variable-name[] . . .

In this formula, the data-type can be one of the types we have used so far (char, int (or one of its variants), bool, float, double, string, etc). Like a normal variable, an array must have a name, represented in our formula as variable-name. The name of the variable is followed by square brackets. Normally, there are various ways you start an array.

Starting an Array with no Values

When starting an array, you may not yet know the values of the array. To create such an array the formula to follow is:

data-type variable-name[length];

In this case, you must specify the number of items that the array will have. Here is an example:

int main()
{
    double numbers[5];
}

Initializing an Array

There are various ways you can create an array. Actually, there are various ways an array can receive its values. The primary way to create an array is to immediately specify the values of its items. This is referred to as initializing the array. The formula to follow is:

data-type variable-name[] = { value_1, value_2, ..., value_X};

Based on this formula, after the square brackets, assign some curly brackets and end the statement with a semicolon. Inside the curly brackets, create a list of the desired values. Here is an example:

int main()
{
    double numbers[5] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}

When creating an array like this, since you already have the (starting) values of the array, you can leave the square brackets empty.

As done above, you can create as many array variables as you want and initialize them.

Practical LearningPractical Learning: Creating an Array

Initializing Each Item

In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case, the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A C-language-based array, which includes C++, is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.

In C++, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

nt main()
{
    double numbers[5];

    numbers[0] = 12.44;
    numbers[1] = 525.38;
    numbers[2] = 6.28;
    numbers[3] = 2448.32;
    numbers[4] = 632.04;
}

Practical LearningPractical Learning: Initializing Each Item of an Array

Practical LearningPractical Learning: Initializing the Items as an Array

Introduction to Accessing the Members of an Array

After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, manipulate or even change its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons of accessing a member of an array is to display its value. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    double numbers[5] = { 12.44, 525.38, 6.28, 2448.32, 632.04 };

    cout << "Number: " << numbers[3];
    cout << endl << "================" << endl;
}

This would produce:

Number: 2448.32
================

Press any key to continue . . .

In the same way, you can access 1, a few or all members of an array.

Remember that, to access a member of an array, pass its index to the square brackets of the variable. If you pass an index higher than the number of items in the array, you would receive an error.

Practical LearningPractical Learning: Accessing the Items of an Array

  1. Change the code as follows:
    using static System.Console;
    
    string[] states = new string[31];
    
    states[0]  = "Guanajuato          ";  states[1]  = "Tamaulipas          "; states[2]  = "Michoacán           ";
    states[3]  = "Coahuila            ";  states[4]  = "Chihuahua           "; states[5]  = "Baja California Sur ";
    states[6]  = "Nayarit             ";  states[7]  = "Puebla              "; states[8]  = "Oaxaca              ";
    states[9]  = "Morelos             ";  states[10] = "Sonora              "; states[11] = "Aguascalientes      ";
    states[12] = "Baja California     ";  states[13] = "Tabasco             "; states[14] = "Jalisco             ";
    states[15] = "México              ";  states[16] = "Guerrero            "; states[17] = "Colima              ";
    states[18] = "Zacatecas           ";  states[19] = "Sinaloa             "; states[20] = "Campeche            ";
    states[21] = "Quintana Roo        ";  states[22] = "Nuevo León          "; states[23] = "Hidalgo             ";
    states[24] = "Tlaxcala            ";  states[25] = "Yucatán             "; states[26] = "Querétaro           ";
    states[27] = "Veracruz            ";  states[28] = "San Luis Potosí     "; states[29] = "Durango             ";
    states[30] = "Chiapas             ";
    
    string[] capitals = new string[] { "Guanajuato                ", "Ciudad Victoria           ", "Morelia                   ",
                                       "Saltillo                  ", "Chihuahua                 ", "La Paz                    ",
                                       "Tepic                     ", "Puebla de Zaragoza        ", "Oaxaca de Juárez          ",
                                       "Cuernavaca                ", "Hermosillo                ", "Aguascalientes            ",
                                       "Mexicali                  ", "Villahermosa              ", "Guadalajara               ",
                                       "Toluca de Lerdo           ", "Chilpancingo de los Bravo ", "Colima                    ",
                                       "Zacatecas                 ", "Culiacán                  ", "San Francisco de Campeche ",
                                       "Chetumal                  ", "Monterrey                 ", "Pachuca                   ",
                                       "Tlaxcala                  ", "Mérida                    ", "Santiago de Querétaro     ",
                                       "Xalapa                    ", "San Luis Potosí           ", "Victoria de Durango       ",
                                       "Tuxtla Gutiérrez          "};
    int[] areasSqrKms = new int[]  {   30608,  80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793,   4893,
                                       179503,  5618, 71446,  24738,  78599, 22357, 63621,  5625, 75539,  57377,
                                       57924,  42361, 64220,  20846,   3991, 39612, 11684, 71820, 60983, 123451, 73289 };
    int[] areasSqrMiles = new int[] {  11818,  30956, 22642,  58519,  95543, 28541, 10739, 13240, 36214,   1889,
                                       69306,   2169, 27585,   9551,  30347,  8632, 24564,  2172, 29166,  22153,
                                       22365,  16356, 24800,   8049,   1541, 15294,  4511, 27730, 23546,  47665, 28297 };
    int[] ordersOfAdmissionToFederation = new int[] {  2, 14,  5, 16, 18, 31, 28,  4,  3, 27,
                                                      12, 24, 29, 13,  9,  1, 21, 23, 10, 20,
                                                      25, 30, 15, 26, 22,  8, 11,  7,  6, 17, 19 };
    
    cout << "===============================================================================");
    cout << "                                                       Area      Order Admission");
    cout << "# State Name           Capital                   Sqr Kms Sqr Miles     to Federation");
    cout << "-------------------------------------------------------------------------------");
    cout << "1  " + states[0]  + " " + capitals[0]  + " " + areasSqrKms[0]  + "  " + areasSqrMiles[0]  + "        " + ordersOfAdmissionToFederation[0]);
    cout << "2  " + states[1]  + " " + capitals[1]  + " " + areasSqrKms[1]  + "  " + areasSqrMiles[1]  + "        " + ordersOfAdmissionToFederation[1]);
    cout << "3  " + states[2]  + " " + capitals[2]  + " " + areasSqrKms[2]  + "  " + areasSqrMiles[2]  + "        " + ordersOfAdmissionToFederation[2]);
    cout << "4  " + states[3]  + " " + capitals[3]  + " " + areasSqrKms[3]  + "  " + areasSqrMiles[3]  + "        " + ordersOfAdmissionToFederation[3]);
    cout << "5  " + states[4]  + " " + capitals[4]  + " " + areasSqrKms[4]  + "  " + areasSqrMiles[4]  + "        " + ordersOfAdmissionToFederation[4]);
    cout << "6  " + states[5]  + " " + capitals[5]  + " " + areasSqrKms[5]  + "  " + areasSqrMiles[5]  + "        " + ordersOfAdmissionToFederation[5]);
    cout << "7  " + states[6]  + " " + capitals[6]  + " " + areasSqrKms[6]  + "  " + areasSqrMiles[6]  + "        " + ordersOfAdmissionToFederation[6]);
    cout << "8  " + states[7]  + " " + capitals[7]  + " " + areasSqrKms[7]  + "  " + areasSqrMiles[7]  + "        " + ordersOfAdmissionToFederation[7]);
    cout << "9  " + states[8]  + " " + capitals[8]  + " " + areasSqrKms[8]  + "  " + areasSqrMiles[8]  + "        " + ordersOfAdmissionToFederation[8]);
    cout << "10 " + states[9]  + " " + capitals[9]  + " " + areasSqrKms[9]  + "  " + areasSqrMiles[9]  + "        " + ordersOfAdmissionToFederation[9]);
    cout << "11 " + states[10] + " " + capitals[10] + " " + areasSqrKms[10] + "  " + areasSqrMiles[10] + "        " + ordersOfAdmissionToFederation[10]);
    cout << "12 " + states[11] + " " + capitals[11] + " " + areasSqrKms[11] + "  " + areasSqrMiles[11] + "        " + ordersOfAdmissionToFederation[11]);
    cout << "13 " + states[12] + " " + capitals[12] + " " + areasSqrKms[12] + "  " + areasSqrMiles[12] + "        " + ordersOfAdmissionToFederation[12]);
    cout << "14 " + states[13] + " " + capitals[13] + " " + areasSqrKms[13] + "  " + areasSqrMiles[13] + "        " + ordersOfAdmissionToFederation[13]);
    cout << "15 " + states[14] + " " + capitals[14] + " " + areasSqrKms[14] + "  " + areasSqrMiles[14] + "        " + ordersOfAdmissionToFederation[14]);
    cout << "16 " + states[15] + " " + capitals[15] + " " + areasSqrKms[15] + "  " + areasSqrMiles[15] + "        " + ordersOfAdmissionToFederation[15]);
    cout << "17 " + states[16] + " " + capitals[16] + " " + areasSqrKms[16] + "  " + areasSqrMiles[16] + "        " + ordersOfAdmissionToFederation[16]);
    cout << "18 " + states[17] + " " + capitals[17] + " " + areasSqrKms[17] + "  " + areasSqrMiles[17] + "        " + ordersOfAdmissionToFederation[17]);
    cout << "19 " + states[18] + " " + capitals[18] + " " + areasSqrKms[18] + "  " + areasSqrMiles[18] + "        " + ordersOfAdmissionToFederation[18]);
    cout << "20 " + states[19] + " " + capitals[19] + " " + areasSqrKms[19] + "  " + areasSqrMiles[19] + "        " + ordersOfAdmissionToFederation[19]);
    cout << "21 " + states[20] + " " + capitals[20] + " " + areasSqrKms[20] + "  " + areasSqrMiles[20] + "        " + ordersOfAdmissionToFederation[20]);
    cout << "22 " + states[21] + " " + capitals[21] + " " + areasSqrKms[21] + "  " + areasSqrMiles[21] + "        " + ordersOfAdmissionToFederation[21]);
    cout << "23 " + states[22] + " " + capitals[22] + " " + areasSqrKms[22] + "  " + areasSqrMiles[22] + "        " + ordersOfAdmissionToFederation[22]);
    cout << "24 " + states[23] + " " + capitals[23] + " " + areasSqrKms[23] + "  " + areasSqrMiles[23] + "        " + ordersOfAdmissionToFederation[23]);
    cout << "25 " + states[24] + " " + capitals[24] + " " + areasSqrKms[24] + "  " + areasSqrMiles[24] + "        " + ordersOfAdmissionToFederation[24]);
    cout << "26 " + states[25] + " " + capitals[25] + " " + areasSqrKms[25] + "  " + areasSqrMiles[25] + "        " + ordersOfAdmissionToFederation[25]);
    cout << "27 " + states[26] + " " + capitals[26] + " " + areasSqrKms[26] + "  " + areasSqrMiles[26] + "        " + ordersOfAdmissionToFederation[26]);
    cout << "28 " + states[27] + " " + capitals[27] + " " + areasSqrKms[27] + "  " + areasSqrMiles[27] + "        " + ordersOfAdmissionToFederation[27]);
    cout << "29 " + states[28] + " " + capitals[28] + " " + areasSqrKms[28] + "  " + areasSqrMiles[28] + "        " + ordersOfAdmissionToFederation[28]);
    cout << "30 " + states[29] + " " + capitals[29] + " " + areasSqrKms[29] + "  " + areasSqrMiles[29] + "        " + ordersOfAdmissionToFederation[29]);
    cout << "31 " + states[30] + " " + capitals[30] + " " + areasSqrKms[30] + "  " + areasSqrMiles[30] + "        " + ordersOfAdmissionToFederation[30]);
    cout << "===============================================================================");
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
    ===============================================================================
                                                           Area      Order Admission
    
    # State Name           Capital                   Sqr Kms Sqr Miles     to Federa
    tion
    -------------------------------------------------------------------------------
    1  Guanajuato           Guanajuato                 30608  11818        2
    2  Tamaulipas           Ciudad Victoria            80175  30956        14
    3  Michoacán            Morelia                    58643  22642        5
    4  Coahuila             Saltillo                   151563  58519       16
    5  Chihuahua            Chihuahua                  247455  95543       18
    6  Baja California Sur  La Paz                     73922  28541        31
    7  Nayarit              Tepic                      27815  10739        28
    8  Puebla               Puebla de Zaragoza         34290  13240        4
    9  Oaxaca               Oaxaca de Juárez           93793  36214        3
    10 Morelos              Cuernavaca                 4893  1889          27
    11 Sonora               Hermosillo                 179503  69306       12
    12 Aguascalientes       Aguascalientes             5618  2169          24
    13 Baja California      Mexicali                   71446  27585        29
    14 Tabasco              Villahermosa               24738  9551         13
    15 Jalisco              Guadalajara                78599  30347        9
    16 México               Toluca de Lerdo            22357  8632         1
    17 Guerrero             Chilpancingo de los Bravo  63621  24564        21
    18 Colima               Colima                     5625  2172          23
    19 Zacatecas            Zacatecas                  75539  29166        10
    20 Sinaloa              Culiacán                   57377  22153        20
    21 Campeche             San Francisco de Campeche  57924  22365        25
    22 Quintana Roo         Chetumal                   42361  16356        30
    23 Nuevo León           Monterrey                  64220  24800        15
    24 Hidalgo              Pachuca                    20846  8049         26
    25 Tlaxcala             Tlaxcala                   3991  1541          22
    26 Yucatán              Mérida                     39612  15294        8
    27 Querétaro            Santiago de Querétaro      11684  4511         11
    28 Veracruz             Xalapa                     71820  27730        7
    29 San Luis Potosí      San Luis Potosí            60983  23546        6
    30 Durango              Victoria de Durango        123451  47665       17
    31 Chiapas              Tuxtla Gutiérrez           73289  28297        19
    ===============================================================================
    Press any key to continue . . .
  3. Press Enter to close the DOS window and return to your programming environment

The Size or Length of an Array

When declaring an array, we saw that you must specify the number of items that the array is made of. Here is an example:

float averagePrice[45];

Depending on how you want to deal with your array, you may sometimes need to increase or decrease its dimension. To do this, you would need to locate the declaration of the array and change its dimension. If the program is long and the array is declared in some unusual place, this could take some time. The alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    const int numberOfItems = 5;
    double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};

    cout << "Distance 1: " << distance[0] << endl;
    cout << "Distance 2: " << distance[1] << endl;
    cout << "Distance 3: " << distance[2] << endl;
    cout << "Distance 4: " << distance[3] << endl;
    cout << "Distance 5: " << distance[4] << endl;
}

This would produce:

Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28

Press any key to close this window . . .

In both cases, t

Members of the array
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28

We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array. Imagine you declare a large array, possibly made of hundreds or thousands of items. If you want to know the number of elements in the array, you wouldn't start counting the number of members. C/C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use is:

sizeof(array-name) / sizeof(data-type)

Imagine you declare an array as follows:

int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12, 127, 4762, 823, 236, 84, 5};

Instead of counting the number of members of this array, you can use the sizeof operator as follows:

int numberOfItemsOfTheArray = sizeof(Number)/sizeof(int);

Techniques of Initializing an Array

A Return Value as an Index

When accessing a member of an array using its index, the value between square brackets must be known. Most of the time, it is a constant, but this is not always the case. The rule is that, at the time you open the square brackets, the value must be known, even if it is not a constant. For example, the value can be returned from a function/method. Here is an example:

#include <iostream>
using namespace std;

int GetIndex();

int main()
{
    double numbers[5];

    numbers[0] = 12.44;
    numbers[1] = 525.38;
    numbers[GetIndex()] = 6.28;
    numbers[3] = 2448.32;
    numbers[4] = 632.04;

    cout << "Number: " << numbers[2];
    cout << endl << "================" << endl;
}

int GetIndex()
{
    return 2;
}

This would produce:

Number: 6.28
================

Press any key to continue . . .

Variables as Members of an Array

We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. You use those values in place of the members of the array. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    double area = 97394.2204;
    double distance = 982.84;
    double level = 27.691;
    double quantity = 237957.704;

    double measures[] = { area, distance, level, quantity };

    cout << "Measure 1: " << measures[0] << endl;
    cout << "Measure 2: " << measures[1] << endl;
    cout << "Measure 3: " << measures[2] << endl;
    cout << "Measure 4: " << measures[3] << endl;
    cout << "===================" << endl;
}

This would produce:

Measure 1: 97394.2
Measure 2: 982.84
Measure 3: 27.691
Measure 4: 237958
===================

Press any key to continue . . .

Array Members from Constants

The values of the members of an array can come from constant variables. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    const double PI = 3.141592653;
    double squareRootOf2 = 1.414;
    double e = 2.718;
    const double radiusOfEarth = 6370; // km
    double ln2 = 0.6931;

    double measures[] = { PI, squareRootOf2, e, radiusOfEarth, ln2 };

    cout << "Measure 1: " << measures[0] << endl;
    cout << "Measure 2: " << measures[1] << endl;
    cout << "Measure 3: " << measures[2] << endl;
    cout << "Measure 4: " << measures[3] << endl;
    cout << "Measure 5: " << measures[4] << endl;
    cout << "===================" << endl;
}

This would produce:

Measure 1: 3.14159
Measure 2: 1.414
Measure 3: 2.718
Measure 4: 6370
Measure 5: 0.6931
===================

Press any key to continue . . .

Expressions as Members of an Array

The values of the members of an array can come from calculations. A calculation can come from an initialized variable or made locally in the curly brackets. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    const double densityOfWater = 1000; // kg/m3 ;
    double massOfEarth = 5.98 * 10e24; // kg
    double earthMoonDistance = 2.39 * 10e5; // miles

    double measures[] =
    {
        densityOfWater, 9.30 * 10.7, massOfEarth, earthMoonDistance
    };

    cout << "Measure 1: " << measures[0] << endl;
    cout << "Measure 2: " << measures[1] << endl;
    cout << "Measure 3: " << measures[2] << endl;
    cout << "=====================" << endl;
}

This would produce:

Measure 1: 1000
Measure 2: 99.51
Measure 3: 5.98e+25
=====================

Press any key to continue . . .

The rule to follow is that, at the time the array is created, the compiler must be able to know exactly the value of each member of the array, no guessing.

Hexadecimal Values as Members of an Array

If the members of an array are integers, you can use decimals, hexadecimal values, or a combination of both. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    int red = 0xFF0000;
    int someColor = 0x800000;

    int colors[5] = { 2510, red, 818203, someColor, 0xF28AC };

    cout << "Color 1: " << colors[0] << endl;
    cout << "Color 2: " << colors[1] << endl;
    cout << "Color 3: " << colors[2] << endl;
    cout << "Color 4: " << colors[3] << endl;
    cout << "Color 5: " << colors[4] << endl;
    cout << "==================" << endl;
}

This would produce:

Color 1: 2510
Color 2: 16711680
Color 3: 818203
Color 4: 8388608
Color 5: 993452
==================

Press any key to continue . . .

Boolean Values as Members of an Array

The members of an array can hold Boolean values. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    bool fullTimeStudents[] = { false, true, true, false, true, false };

    cout << "Is a full-time student? " << fullTimeStudents[0] << endl;
    cout << "Is a full-time student? " << fullTimeStudents[1] << endl;
    cout << "Is a full-time student? ";
    if(fullTimeStudents[2] == 0)
        cout << "False" << endl;
    else
        cout << "True" << endl;
    cout << "Is a full-time student? ";
    if (fullTimeStudents[3] == 1)
        cout << "True" << endl;
    else
        cout << "False" << endl;

    cout << "Is a full-time student? ";
    if (fullTimeStudents[4] == 0)
        cout << "No" << endl;
    else
        cout << "Yes" << endl;

    cout << "Is a full-time student? ";
    if (fullTimeStudents[5] == 1)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    cout << "==============================" << endl;
}

This would produce:

Is a full-time student? 0
Is a full-time student? 1
Is a full-time student? True
Is a full-time student? False
Is a full-time student? Yes
Is a full-time student? No
==============================

Press any key to continue . . .

Each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:

#include <iostream>
using namespace std;

int main()
{
    long long house1Value = 537905;
    long long house2Value = 707000;

    bool conparisons[] = { 25 < 10, house1Value == house2Value, true };

    cout << "25 < 10? " << conparisons[0] << endl;
    cout << "Both houses have the same market value? " << conparisons[1] << endl;
    cout << "The value is True: " << conparisons[2];
    
    cout << endl << "--------------------------------------------" << endl;

    cout << "Not(25 < 10)? " << !conparisons[0] << endl;
    cout << "The houses have different market values: " << !conparisons[1] << endl;
    cout << "The value is False: " << !conparisons[2];
    cout << endl << "============================================" << endl;
}

This would produce:

25 < 10? 0
Both houses have the same market value? 0
The value is True: 1
--------------------------------------------
Not(25 < 10)? 1
The houses have different market values: 1
The value is False: 0
============================================

Press any key to continue . . .

A Returned Value as a Member of an Array

The value of a member of an array can be the returned value of a method. Here is an example:

#include <iostream>
using namespace std;

int GetIndex();

double GetDistance()
{
    return 632.04;
}

int main()
{
    double numbers[5];

    numbers[0] = 12.464;
    numbers[1] = 525.38;
    numbers[GetIndex()] = 6.2855;
    numbers[3] = 2448.352;
    numbers[4] = GetDistance();

    cout << "Number 1: " << numbers[0] << endl;
    cout << "Number 2: " << numbers[1] << endl;
    cout << "Number 3: " << numbers[2] << endl;
    cout << "Number 4: " << numbers[3] << endl;
    cout << "Number 5: " << numbers[4] << endl;
    cout << "==================" << endl;
}

int GetIndex()
{
    return 2;
}

This would produce:

Number 1: 12.464
Number 2: 525.38
Number 3: 6.2855
Number 4: 2448.35
Number 5: 632.04
==================

Press any key to continue . . .

As a result, both the index and the value can come from functions.

Arrays and Functions

Introduction

An array is primarily a type in its own right. As such, it can be used in some ways we have dealt with data types so far. The main issue to keep in mind is that the type of an array is a series of values.

An Array Passed as Argument

Like a regular variable, an array can be passed as argument. To proceed, in the parentheses of a function, provide the data type, a name for the parameter, and empty square brackets. Here is an example:

void ShowPoints(int points[4])
{
}

When an array has been passed to a function, it can be used in the body of the function as any array would be, following the rules of array variables. For example, you can display its values. The simplest way you can use an array is to display the values of its members. This could be done as follows:

#include <iostream>
using namespace std;

void CreateCoordinate(int pts[4])
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
}

In the above examples, we provided the number of elements of the array in the parentheses of the function. In reality, that number is not required. This means that you can leave the square brackets of the parameter empty. Here is an example:

#include <iostream>
using namespace std;

void CreateCoordinate(int pts[])
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
}

Calling an Arrayed Function

To call a function that takes an array as argument, simply type the name of the array in the parentheses of the called function. Here is an example:

#include <iostream>
using namespace std;

void CreateCoordinate(int pts[])
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
}

int main()
{
    int coords[] = { 12, 5, 625, -2 };

    cout << "Points Coordinates";
    cout << "\n----------------------\n";

    CreateCoordinate(coords);

    cout << "======================\n";
}

This would produce:

Points Coordinates
----------------------
P(12, 5)
Q(625, -2)
======================

Press any key to close this window . . .

Declaring a Function

Remember that, in C++, you can declare a function before defining. This is also valid if the function takes an array as argument. Here is an example:

#include <iostream>
using namespace std;

void CreateCoordinate(int pts[4]);

int main()
{
    int coords[] = { 12, 5, 625, -2 };

    cout << "Points Coordinates";
    cout << "\n----------------------\n";

    CreateCoordinate(coords);

    cout << "======================\n";
}

void CreateCoordinate(int pts[4])
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
}

When declaring a function that uses an array as a parameter, you don't have to provide a name for the parameter. For such a parameter, you can type the square brackets on the right side of the data type. When defining the function, you must specify the name of the parameter. Therefore, the above function can be declared as follows:

#include <iostream>
using namespace std;

void CreateCoordinate(int[4]);

int main()
{
    int coords[] = { 12, 5, 625, -2 };

    cout << "Points Coordinates";
    cout << "\n-------------------\n";

    CreateCoordinate(coords);

    cout << "===================\n";
}

void CreateCoordinate(int pts[4])
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
}

Passing a Varied Number of Parameters

When you pass an array as argument or pass a combination of arrays and non-array arguments, when you call the function, you must pass the exact number of arguments. That is, you must know the number of arguments the function will process. An alternative to this is to pass only one array as argument. Then, when, or every time, you call the function, you can pass any number of values you want. That is, at one time you can call the function and pass 2 values. At another time, you can call the same function but pass more arguments to it.

To create a function that receives a varied number of arguments, in the parentheses of the method, specify a parameter that is an array. After the square brackets of the parameter, type three periods .... Here is an example:

void ShowPoints(int points[]...)
{

}

After creating the parameter, in the body of the function, you can use it like you do any array. When calling the function, you can pass as many arguments as you want. Here are examples:

#include <iostream>
using namespace std;

void CreateCoordinate(int pts[]...)
{
    cout << "P(" << pts[0] << ", " << pts[1] << ")\n";
    cout << "Q(" << pts[2] << ", " << pts[3] << ")\n";
    cout << "--------------------------\n";
}

int main()
{
    int coords[] = { 12, 5, 8, -2 };

    cout << "Points Coordinates";
    cout << "\n==========================\n";
    CreateCoordinate(coords);

    int values[] = { -3, 7 };
    CreateCoordinate(values);

    int nbrs[] = { 6, 9, 13, 11, 5, 12 };
    CreateCoordinate(nbrs);
}

This would produce:

Points Coordinates
==========================
P(12, 5)
Q(8, -2)
--------------------------
P(-3, 7)
Q(-858993460, -858993460)
--------------------------
P(6, 9)
Q(13, 11)
--------------------------

Press any key to close this window . . .

It's important to know that the function that receives a ... argument doesn't know the number of values it will receive when it is called. This means that you must find a way to access the arguments and you must find a way for the function to know the number of arguments it received.

The main() Function of an Application

Every C++ (console) application must have a function named main. That function is the part where tha application processing starts. Therefore, if you want your application to do something as soon as it comes up, you can put appropriate code in that function. To make this possible, the C++ language allows you to pass a string array to the main() function. This is done as follows:

int main(string args[])
{

}

In fact, if you create a C++ Console Application in Microsoft Visual Studio, the generated project would have a Main() function that has a string[] array. Here is the content of the code document created from the New Project dialog box:

int main(string args[])
{
    cout << "Hello World!");
}

As mentionned so far about arguments, you can use or ignore the argument of the Main() function. If you ignore that argument, there will not be any positive value or never impact to your application. Otherwise, when the user executes your application, you can get and process the argument of the Main() function. Because that argument is an array, it can contain any number of values. Each can be accessed by its position.


Previous Copyright © 2000-2026, FunctionX Monday 08 May 2023 Next