C++ Primer Plus Chapter 6 Exercise 2

c plus plusThe trick to exercise 2 is not just getting it to average numbers, but getting it to produce how many where over the average. See my solution to this below:

2. Write a program that reads up to 10 donation values into an array of double. The program
should terminate input on non-numeric input. It should report the average of the
numbers and also report how many numbers in the array are larger than the average.

#include <iostream>

const int max = 10;

int main()
{
double donations[max];

std::cout << "Enter your donation amounts\n\n";
std::cout << "Donation #1: ";

int i = 0;
while(i < max && std::cin >> donations[i])
{
if(++i < max)
std::cout << "Donation #" << i+1 << ": ";
}

double total = 0.0;
int over = 0;
for(int j = 0; j < i; j++)
{
total+=donations[j];
}

int avg = total / i;

for(int j = 0; j < i; j++)
{
if(donations[j] > avg)
over++;
}

std::cout << "\n";
std::cout <<  avg << " Average of donations\n";
std::cout << "Number of donations over the average amount " << over << "\n";

return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s