14. Operations on Arrays

Size of an Array

To complete the solution of the problem, the search for the minimum value has to be written down again. Before doing that, a question needs to be answered: how many elements are there in the array data?

The unique answer to that question cannot be given during the writing of the program. We could add a counter to the do while loop to make it count the number of elements. However, there is a much better solution: an array can always somehow 'tell' the number of elements it contains. The number of elements of the array data can be obtained by the expression int(data.size()), which might be employed like this:

int dataSize= int(data.size());

This statement will introduce a variable named dataSize, which will be assigned the number of elements of the array data.

The remaining part of the program will find the smallest element, although by now, you should be able to write it yourself. The code of the complete program is given below:

#include <iostream>
#include <vector>

int main()
    std::vector<double> data;
    double input;
    do  {
        std::cin >> input;
    int dataSize = int(data.size());
    double min = data[0];
    for (int i=1; i<dataSize; i++)
        if (data[i] < min)
            min = data[i];

    std::cout << "The minimum is: " << min << std::endl;         

On executing the program we could get an output similar to this:

The minimum is: 5
Warning! Remember that you can use a piece of code from the given program whenever you need a program to read in some input data until the input is terminated by the end-of-input value.