Hi guys,
I am trying to write a program that takes in a file, which has the last name first name and grade of a student. I then need to sort the grades from highest score to lowest with the corresponding names and then calculate the average grade. I have successfully opened the file and calculated the average but cannot figure out the sorting. This is a homework assignment so I would really just like pointers on how to do this. Thank you for the help in advance!
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
main(){
FILE *data;
char line[35];
char grade[35];
const int a = 34;
int i, j, l, t;
float average, sum, g;
data = fopen("/home/varnes/hw06/hw6_grades.txt", "r");
if ( data == NULL ){
printf("Error: Cannot open file\n");
exit(1);
}
for ( j = 0; j < a; j++){
while (fgets (line, sizeof(line), data) != NULL){
printf(line);
for ( l = 0; l < 1; l++){
strncpy(grade, line+21, 26);
g = atof(grade);
sum += g;
}
for(i = 0; i < 33; i++){
if((grade[i]) > (grade[i+1])){
t = grade[i];
grade[i] = grade[i+1];
grade[i+1] = t;
}
}
}
printf("\n%c ", grade[i]);
}
average = sum/a;
printf("\nSum is: %f", sum);
printf("\nAverage grade: %f\n", average);
}