/* This program opens a file called "scores" that is formatted into * five columns: one with the social security number of the student, * and then the grades for program 1, program 2, test 1, and test 2. * * It figures out the weighted average for each student according to * * prog1 = 10% of grade * prog2 = 20% of grade * test1 = 30% of grade * test2 = 40% of grade * * It also prints the SSN of the student with the best average, and the * average for the class. * * Programs are graded on a scale of 1..10, test from 1..100. We want * the average to be calculated in terms of 1..100. */ #include int main () { int ssn, /* current SSN */ best_ssn, /* SSN of best student */ n; /* number of students */ float average, /* average for current student */ class_average, /* average for class */ best_average, /* average for best student */ prog1, /* grades for prog1, prog2, ... */ prog2, test1, test2; FILE *f; /* file pointer */ /* open the "scores" file for reading */ f = fopen ("scores", "r"); /* initialize averages, etc. to 0 */ class_average = 0.0; best_average = 0.0; best_ssn = 0; n = 0; /* read in the first student record */ fscanf (f, "%d %f %f %f %f", &ssn, &prog1, &prog2, &test1, &test2); /* while not at the end of this file... */ while (!feof (f)) { /* one more student */ n++; /* figure out average, scaling programs up to 1..100 */ average = 0.10 * (prog1 * 10) + 0.20 * (prog2 * 10) + 0.30 * test1 + 0.40 * test2; /* accumulate averages in class_average, later we * will divide by n */ class_average += average; /* if this average is better than current best average... */ if (average > best_average) { /* ... save it and the ssn */ best_average = average; best_ssn = ssn; } /* print out the current student's information */ printf ("SSN %d; grade %6.2f\n", ssn, average); /* get another student record */ fscanf (f, "%d %f %f %f %f", &ssn, &prog1, &prog2, &test1, &test2); } /* close the file */ fclose (f); /* print the average and SSN for the best student */ printf ("best student has ssn %d with score %6.2f\n", best_ssn, best_average); /* figure out class average (dividing the sum by number of students) */ class_average /= n; /* print class average */ printf ("class average is %6.2f\n", class_average); }