Skip to content

Instantly share code, notes, and snippets.

@mahata
Created September 16, 2011 04:41
Show Gist options
  • Save mahata/1221212 to your computer and use it in GitHub Desktop.
Save mahata/1221212 to your computer and use it in GitHub Desktop.
C++ Primer 7.2
#include <iostream>
void inputScore(int * score_card, int score_size);
void displayScore(int * score_card, int score_size);
double getAverageScore(int * score_card, int score_size);
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
const int SCORE_SIZE = 10;
int score_card[SCORE_SIZE];
// init
int i = 0;
for (; i < SCORE_SIZE; i++) { score_card[i] = 0; }
// input score
inputScore(score_card, SCORE_SIZE);
// display score
displayScore(score_card, SCORE_SIZE);
// calculate average score
double average = getAverageScore(score_card, SCORE_SIZE);
// display average score
cout << "average: " << average << endl;
// output
return 0;
}
void inputScore(int * score_card, int score_size)
{
using namespace std;
int i = 0;
for (; i < score_size; i++) {
cout << "Please enter #" << (i + 1) << " golf score (enter 0 to stop): ";
int score;
cin >> score;
if (0 == score) { break; }
score_card[i] = score;
}
}
void displayScore(int * score_card, int score_size)
{
using namespace std;
int i = 0;
for (; i < score_size; i++) {
if (0 == score_card[i]) { return; }
cout << i << ": " << score_card[i] << endl;
}
}
double getAverageScore(int * score_card, int score_size)
{
double sum = 0;
int i = 0;
for (; i < score_size; i++) {
if (0 == score_card[i]) { break; }
sum += score_card[i];
}
return sum / i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment