// Player Scores
// Track 4 players' scores in a game
// We want to be able to:
// * store integer scores
// * print out everyone's current score
// * say who's winning
// * print out the total of all the scores? (Maybe TODO)
// Marc Chee (cs1511@cse.unsw.edu.au), October 2020
#include
#define NUM_PLAYERS 4
void printScores(int playerScores[NUM_PLAYERS]);
int findWinner(int currentScores[NUM_PLAYERS]);
int main(void) {
// declare an array of 4 integers
int scores[NUM_PLAYERS] = {50, 12, 67, 89};
// The second team was just put in here as an example to show
// how a function can be given different inputs
int scoresTeam2[NUM_PLAYERS] = {0};
printScores(scores);
printScores(scoresTeam2);
// set up initial values
// This next section isn't necessary, but it's
// here to show how to access individual elements
scores[0] = 55;
scores[1] = 17;
scores[2] = 72;
scores[3] = 94;
printScores(scores);
int winnerIndex = findWinner(scores);
printf(
"The current leader is Player %d with %d points.\n",
winnerIndex,
scores[winnerIndex]
);
}
// A function that prints out all the current scores given
// in playerScores.
void printScores(int playerScores[NUM_PLAYERS]) {
int i = 0;
while (i < NUM_PLAYERS) { // we have seen i elements of the array
printf("Player %d has %d points.\n", i, playerScores[i]);
i++;
}
}
// findWinner will loop through currentScores
// and return the index of the current highest score
int findWinner(int currentScores[NUM_PLAYERS]) {
// store the current highest index
int highestIndex = 0;
// loop through and if we see anything higher
// replace the current highest
int i = 1;
while (i < NUM_PLAYERS) {
if (currentScores[i] > currentScores[highestIndex]) {
// score is higher than previous highest
// replace previous highest
highestIndex = i;
}
i++;
}
// highestIndex is now the index that contained the highest value
return highestIndex;
}