How to Use an Array in C++ - dummies

By Stephen R. Davis

An array is a sequence of variables in C++ that shares the same name and that is referenced using an index. The following C++ program inputs a sequence of integer values from the keyboard until the user enters a negative number. The program then displays the numbers input and reports their sum.

// ArrayDemo - demonstrate the use of arrays
//             by reading a sequence of integers
//             and then displaying them and their sum
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// prototype declarations
int readArray(int integerArray[], int maxNumElements);
int sumArray(int integerArray[], int numElements);
void displayArray(int integerArray[], int numElements);
int main(int nNumberofArgs, char* pszArgs[])
    // input the loop count
    cout << "This program sums values entered "
         << "by the usern";
    cout << "Terminate the loop by entering "
         << "a negative numbern";
    cout << endl;
    // read numbers to be summed from the user into a
    // local array
    int inputValues[128];
    int numberOfValues = readArray(inputValues, 128);
    // now output the values and the sum of the values
    displayArray(inputValues, numberOfValues);
    cout << "The sum is "
         << sumArray(inputValues, numberOfValues)
         << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    return 0;
// readArray - read integers from the operator into
//             'integerArray' until operator enters neg.
//             Return the number of elements stored.
int readArray(int integerArray[], int maxNumElements)
    int numberOfValues;
    for(numberOfValues = 0;
        numberOfValues < maxNumElements;
        // fetch another number
        int integerValue;
        cout << "Enter next number: ";
        cin  >> integerValue;
        // if it's negative...
        if (integerValue < 0)
            // ...then exit
        // ... otherwise store the number
        // into the  storage array
        integerArray[numberOfValues] = integerValue;
    // return the number of elements read
    return numberOfValues;
// displayArray - display the members of an
//                array of length sizeOfloatArray
void displayArray(int integerArray[], int numElements)
    cout << "The value of the array is:" << endl;
    for (int i = 0; i < numElements; i++)
        cout << i << ": " << integerArray[i] << endl;
    cout << endl;
// sumArray - return the sum of the members of an
//            integer array
int sumArray(int integerArray[], int numElements)
    int accumulator = 0;
    for (int i = 0; i < numElements; i++)
        accumulator += integerArray[i];
    return accumulator;

The program ArrayDemo begins with prototype declarations of the functions readArray(), sumArray(), and displayArray(), which it will need later. The main program starts with a prompt to the user to input data to be summed. The program then declares an array inputValues[] to be used to store the values input by the user.

The main program passes this array to readArray(), along with the length of the array — readArray() cannot read more than 128 values even if the user does not enter a negative number since that’s all the room allocated in the inputValues[] array.

The array inputValues is declared as 128 integers long. If you’re thinking that this must be more than enough, don’t count on it. No matter how large you make the array, always put a check to make sure that you do not exceed the limits of the array. Writing more data than an array can hold causes your program to perform erratically and often to crash.

The main function then calls displayArray() to print the contents of the array. Finally, the function calls sumArray() to add the elements in the array.

The readArray() function takes two arguments: the integerArray[] into which to store the values it reads and maxNumElements, the maximum number of integer values for which there is room at the inn. The function begins with a for loop that reads integer values. Every non-negative value that the function reads is saved into integerArray[]. The first element goes into integerArray[0], the second into integerArray[1], and so forth.

Once the user enters a negative number, the program breaks out of the loop and returns the total numberOfValues input.

The displayArray() function also uses a for loop to traverse the elements of the array, starting at 0 and continuing to the last element, which is numElements – 1. The final function, sumArray(), also iterates through the array but sums the elements stored there into accumulator, which it then returns to the caller.

Notice, yet again, that the index i in the displayArray() and sumArray() functions is initialized to 0 and not to 1. In addition, notice how the for loop terminates as soon as i reaches numElements. The output from a sample run appears as follows:

This program sums values entered by the user
Terminate the loop by entering a negative number
Enter next number: 10
Enter next number: 20
Enter next number: 30
Enter next number: 40
Enter next number: -1
The value of the array is:
0: 10
1: 20
2: 30
3: 40
The sum is 100
Press Enter to continue...

Just to keep non-programmers guessing, the term iterate means to traverse through a set of objects such as an array. Programmers say that the preceding functions iterate through the array.