10. Arrays

Reading Data into Arrays

It is time to readdress the first part of our initial problem: write a program that reads in 10 values, then writes them out in the reverse order, i.e. from the last to the first.

An array for storing input data will be used, in this case an array of 10 elements. Such an array can be introduced by the following statement:

    vector<double> inputData(10);

This statement introduces a variable inputData as an array having 10 elements of type double. In addition, it sets every element of this array to zero.

To read in and store ten numbers from standard input into the variable inputData we can use a for loop:

    for(int i=0; i<10; i++)
        cin >> inputData[i];

Again the idiom of using loop variables for iterating through array elements has been employed.

To complete the program, we just need to print out the elements of this array, beginning with the last one. Let us use a for loop again:

    for(int i=0; i<10; i++)
        cout << inputData[9-i] << endl;

The variable i ranges from 0 to 9 in this for loop, but the index expression is 9-i, which has the effect of reversing the order.

The second part of the problem was: Write a program that first reads in a natural number n. Then it should read in n numbers. It should write out those n numbers in the reverse order. Here is the entire solution:

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    cout << "Type in the number n: ";
    int n;    
    cin >> n;
    
    cout << "Type in " << n << " numbers:" << endl;  
    vector<double> inputData(n);
    for(int i=0; i<n; i++)
        cin >> inputData[i];

    cout << "Output in the reverse order:" << endl; 
    for(int i=0; i<n; i++)
        cout << inputData[n-1-i] << " ";    
    cout << endl;
}

To separate the output data, the program uses a single space character instead of breaking to a new line after outputting each value. That is why the output values will all be printed out on a single line.

The output looks like this:

Type in the number n: 6
Type in 6 numbers:
11 22.2 33 -44 5.55 6
Output in the reverse order:
6 5.55 -44 33 22.2 11

You might be wondering why the program is allowed to introduce the variable i twice, once in each for loop? The answer is: because loop variables get removed once the loop has been completed.