All pastes #259168 Raw Edit

Untitled

public text v1 · immutable
#259168 ·published 2006-11-27 04:33 UTC
rendered paste body
#include <stdio.h>

// Function prototypes
int get_scores(int list[]);
double get_mean(int list[], int n);
void selection_sort(int list[], int n);
void display_scores(int list[], int n);

// Global variables
int scores[75];

int main(void) {
  int nos;
  double avg;

  nos = get_scores(scores);
  selection_sort(scores, nos);
  avg = get_mean(scores, nos);
  printf("The average of the scores is %f\n\n", avg);
  printf("The highest score is %d\n", scores[0]);
  printf("The lowest score is %d\n\n", scores[nos - 1]);
  display_scores(scores, nos);

  return 0;
}

/**
 * Pass a pointer to the first array element 
 * and have the array populated and have the function return the number of elements in the array
 **/
int get_scores(int list[]) {
  FILE *scores_file;
  int temp_score;
  int i = 0;

  scores_file = fopen("scores.txt", "r");
  while(fscanf(scores_file, "%d", &temp_score) != EOF) {
    list[i] = temp_score;
    i++;
  }

  return i;
}

/**
 * Calculate the average of the scores and return this average
 */
double get_mean(int list[], int n) {
  double sum;
  int i;

  for(i = 0; i < n - 1; i++) {
    sum += list[i];
  }
  sum = sum / n;

  return sum;
}

/**
 * Sort the array from high to low with the selection sort algorithm
 */
void selection_sort(int list[], int n) {
  int i, j, max, temp;

  for(i = n - 1; i >= 0; i--) {
    max = i;
    for(j = i - 1; j >= 0; j--) {
      if(list[j] < list[max]) {
	max = j;
      }
      temp = list[i];
      list[i] = list[max];
      list[max] = temp;
    }
  }
}

/*
 * Display the scores with a tab between each one
 */
void display_scores(int list[], int n) {
  int i;

  printf("The scores in descending order:\n");
  for(i = 0; i < n - 1; i++) {
    printf("%d\t", list[i]);
  }
  printf("\n");
}