10. Arrays

Printing out Arrays

When working with an array, it is often necessary to print out elements of the array, from the first element to the last. Let us suppose we are given the following array containing seven elements:

    vector<double> data = {1, 8, -3, 9, 2, -13, 5};

A clumsy way to print out the elements of this array would be to use one statement for each element:

    cout << data[0] << endl;
    cout << data[1] << endl;
    cout << data[2] << endl;
    …

What would happen if the array had 100 elements, instead of just 7? We are not going to write this in such an inflexible and backbreaking manner, are we not? If you thought that there has to be a better way to do this, which includes using a for loop, then you were pretty spot on:

    for(int i=0; i<7; i++)
        cout << data[i] << endl;

In the last statement, the loop variable i is used as an index of array data. An index can be given by any expression, thus it can be given by a variable.

The important idea to learn from this example is that loop variables can be used for iterating through array elements. You will see this idiom pop up frequently in many programs.

Besides the type int, there are other types in C++ used for representing integers. Those types are called integral types.

In the given example, the loop variable i is of type int. Indices of arrays have to be integers, so whenever a variable is used as an index, it should be of an integral type. Considering that loop variables typically count the ordinal number of a loop iteration, which is always an integer, it is also customary to make loop variables to be of type int. This convention will be followed in all of our future programs, as well.

When writing loops that iterate through elements of an array, it is crucial to pay attention to boundary conditions, that is, to correctly specify the range of indices. Since array indices begin with the number 0, the starting and final value of the loop variable i have been appropriately changed. The starting value is now 0, and the final value is 6. Notice that we have used the operator '<' instead of the operator '<='. Therefore, the variable i will range from 0 to 6, not from 0 to 7. Again, this is an idiomatic manner of writing for loops in the programming language C++.

In total, the line:

    for(int i=0;i<7;i++)

can be read as: "for each i from 0, while i is less than 7"

The entire program would be written as follows:

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

int main()
{
    vector<double> data = {1, 8, -3, 9, 2, -13, 5};

    for(int i=0;i<7;i++)
        cout << data[i] << endl;
}