11. Counter, Arithmetic Mean and Division by Zero

Arithmetic Mean

Let us modify the preceding program so that it prints out the mean value of inputs greater than 10. The problem would be stated as: Write a program that reads in 7 numbers, then it prints out the arithmetic mean of input values greater than 10.

Arithmetic mean value is calculated by dividing the sum of numbers in a series by the number of numbers in that series. Thus, to calculate the mean, we need to calculate the sum of numbers in question and the number of numbers in question. Having obtained both of these values, it is then a simple task to calculate the mean value itself.

Even though the summing up algorithm and the counter algorithm could be written separately, each in its own for loop, we have decided to integrate both of them into a single loop like this:

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

int main() 
{ 
    vector<double> inputValues(7);    
    cout << "Type in 7 numbers:" << endl;
    for (int i=0;i<7;i++)
        cin >> inputValues[i];
    
    int count = 0;
    double sum = 0;
    for (int i=0;i<7;i++)
        {
        if (inputValues[i] > 10)
            {
            sum += inputValues[i];
            count++;
            }
        }

    cout << "The mean value of input numbers greater than 10 is: "
         << sum/count << endl;
}

The first step of summing up algorithm and counter algorithm is in the front of the for loop:

    int count = 0;
    double sum = 0;

Inside the for loop, the program has to count and add up all the numbers that satisfy the given condition. To check the condition, the program uses an if statement that controls a block of two statements:

        if (inputValues[i] > 10)
            {
            sum += inputValues[i];
            count++;
            }

The output of the program could be:

Type in 7 numbers:
4 9 23 100 -77 10 37
The mean value of input numbers greater than 10 is: 42.5