// A Score Tracker for players in a game
// Also a demo of arrays and functions
// Marc Chee (cs1511@cse.unsw.edu.au) June 2020
#include <stdio.h>
#define NUM_PLAYERS 4
void print_scores(int score_array[], int length);
int winning_player(int score_array[], int length);
int main(void) {
int scores[NUM_PLAYERS] = {0};
// directly assign scores to players
scores[0] = 12;
scores[1] = 76;
scores[2] = 34;
scores[3] = 56;
print_scores(scores, NUM_PLAYERS);
int winner_index = winning_player(scores, NUM_PLAYERS);
printf("Player %d is currently winning the game.\n", winner_index + 1);
}
// Prints out the players and their scores, one per line
void print_scores(int score_array[], int length) {
int i = 0;
while (i < length) { // have visited i elements
printf("Player %d's score is %d.\n", i + 1, score_array[i]);
i++;
} // i == length
}
// Returns the index of the player with the highest score
// Assumes scores are positive
int winning_player(int score_array[], int length) {
// set the highest to a very low number
int highest = -1;
// set the highest index to an index that's not in the array
int highest_index = -1;
// loop through the scores array
int i = 0;
while (i < length) {
// for each element, check if it's higher than the highest (we've seen so far)
if (score_array[i] > highest) {
// if it's higher, replace the highest
// keep track of the index of the highest score
highest = score_array[i];
highest_index = i;
}
i++;
} // i == length
return highest_index;
}
Resource created Friday 22 May 2020, 10:26:38 AM, last modified Thursday 18 June 2020, 07:05:45 PM.
file: score_tracker.c