C++ Primer Plus Chapter 7 Exercise 2

c plus plusExercise 2 is a good lesson in functions. You will be forced to use a function for every requirement of the program. In addition, you will have to be inventive with how you terminate the program early and still calculate a running average. See my source below:
2. Write a program that asks the user to enter up to 10 golf scores, which are to be stored
in an array. You should provide a means for the user to terminate input prior to entering
10 scores. The program should display all the scores on one line and report the average
score. Handle input, display, and the average calculation with three separate array-
processing functions.

#include <iostream>

const int maxSize = 10;

// Prototypes
int input(int scores[], int arSize);
double avg(int scores[], int arSize);
void display(int scores[], int arSize);

int main()
{
int scores[maxSize];
int arSize = input(scores, maxSize);
display(scores, arSize);
std::cout << "Average score: " << avg(scores, arSize);
return 0;
}

int input(int scores[], int arSize)
{
double score;
int count = 0;
std::cout << "Enter up to " << maxSize << " scores (press -1 to terminate)\n"; // Loop up to 10 times
for(int i = 0; i < maxSize; i++) // Loop until maxSize
{
std::cout << "Enter Score #" << (i + 1) << ": ";
std::cin >> score;
if(score > 0)
{
scores[i] = score; // assign score to score[i]
count++;
}
else
break;

}
return count; // return something sice fucntion is not void.

}

double avg(int scores[], int arSize)
{
double total = 0;
for(int i = 0; i < arSize; i++) // Loop as many times as was actually inputted
{
total += scores[i];
}
return total/arSize;
}

void display(int scores[], int arSize)
{
std::cout << "Scores: ";
for(int i = 0; i < arSize; i++) // Loop as many times as was actually inputted
{
std::cout << scores[i] << " "; // Print to one line
}
}
About these ads

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