Accelerated C++ Solution to Exercise 4-7

Exercise 4-7

Write a program to calculate the average of the numbers stored in a vector<double>.


In comparison to the previous exercises in this chapter 4, this problem is (fortunately)  quite simple to solve.

Solution Strategy:

  1. In the main program, have a while loop to read individual value x (of type double) one by one, and parse to a container called numbers (of type vector<double>).
  2. Create a function compute_average that reads the vector<double> numbers, and return the average value (of type double).
  3. This function will throw a domain_error if the vector is empty (i.e. no numbers provided). This is to avoid the disgraceful error as a result of division by zero. (note that the average is computed as sum of the values inside the vector, divided by the size of the vector. If the size of the vector is zero, we will have the division by zero issue).
  4. Within the main program, display the average value using the std::cout.

The Program

Since we are only dealing with one function, it may be simpler to just define the function at the top of the main.cpp file (rather than partitioning the programing into multiple C++ header and source files).

The program looks like this.

#include <iostream>   // cout, cin, endl
#include <vector>     // vector
#include <stdexcept>  // domain_error

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::domain_error;

double compute_average(const vector<double>& v)
    typedef vector<double>::size_type vtype;
    vtype v_size = v.size();

    if (v_size == 0) throw domain_error("no numbers provided - vector is empty!");

    double sum = 0;
    for (vtype i = 0; i != v_size ; ++i)
        sum += v[i];
    return sum / v_size;

int main()
    double x;
    vector<double> numbers;
    while (cin >> x)
        cout << "Average: " << compute_average(numbers);
    catch (domain_error e)
        cout << e.what();
    cout << endl;

    return 0;


Test 1

The average value of the 6 numbers is computed correctly.

2.5 3.5 4.5 5.5 8.5 9.5
Average: 5.66667

Test 2

The average value of the 5 numbers is computed correctly.

Average: 333.33

Test 3

For empty vector (no number provided scenario), the try and catch block successfully throw the domain_error message,

no numbers provided - vector is empty!


Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

Leave a reply