Sum and Average

Now that you can go through a vector, let's look at what loops are used for most often. The first pattern adds everything up. Say you have the prices of the things in your shopping cart and want the total:

std::vector<int> prices = {120, 45, 300, 85};
int total = 0;
for (int price : prices) {
    total += price;
}
std::cout << "Total: " << total << std::endl;
Total: 550

The variable total collects the sum. It starts at 0, because before you add anything, the sum is zero. In each iteration, total += price adds one price: after the first iteration, total is 120, then 165, 465 and finally 550.

Where each line goes matters:

  • int total = 0; goes before the loop, so that it runs only once. Inside the loop's block, it would create a new total with the value 0 in every iteration. And after the loop, total wouldn't exist at all: a variable created in a block exists only in that block, so Clang would report error: use of undeclared identifier 'total'.
  • std::cout goes after the loop, when the sum is complete. Inside the loop, it would print every partial sum: 120, 165, 465 and 550.

The average is the sum divided by the number of values, and the number of values is the size of the vector. But watch out for integer division. After the loop above, this prints:

double average = total / prices.size();
std::cout << "Average: " << average << std::endl;
Average: 137

The real average is 137.5. Both total and prices.size() are whole numbers, so / divides them as whole numbers and drops the .5, just like 7 / 2 gives 3. Storing the result in a double doesn't help, because by then the division is already done. The fix is to collect the sum in a double from the start. A decimal number divided by a whole number gives a decimal number:

std::vector<int> prices = {120, 45, 300, 85};
double total = 0;
for (int price : prices) {
    total += price;
}
std::cout << "Total: " << total << std::endl;

double average = total / prices.size();
std::cout << "Average: " << average << std::endl;
Total: 550
Average: 137.5

A double that holds a whole number prints without a decimal point, so the total is still 550. And use prices.size() rather than the number 4: when you add another price to the vector, the average will still be right.

Instructions

The vector points holds your points from four tests. Create a variable total with the value 0. Then go through points with a for loop and add each value to total with +=.

After the loop, print the sum as Total: 94.

At the end of the program, create a variable average of type double with the average: total divided by the size of the vector. Print it as Average: 23.5. If your program prints Average: 23, read the part about integer division again.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/13