I need to print all students which average grade is bigger or equal to given average.
#include <stdio.h>
struct Student {
char name[20], surname[20];
int grades[50];
int number_of_grades;
};
void print_average(struct Student students[], int n, double avarage) {
double avarage_grade;
int i;
for (i = 0; i < n; i ) {
avarage_grade =
(double)(students[i].grades[i]) / students[i].number_of_grades;
if (avarage_grade >= avarage)
printf("%s %s\n", students[i].surname, students[i].name);
}
}
int main() {
struct Student students[] = {{"Meho", "Behic", {10, 9}, 2},
{"Meho", "Aehic", {10, 8}, 2},
{"Meho", "Cehic", {10, 9, 8, 7, 6}, 5},
{"Meho", "Dehic", {6, 9}, 2},
{"Meho", "Zehic", {10}, 1},
{"Meho", "Oehic", {10, 9, 9, 9}, 4}};
print_average(students, 6, 9.2);
return 0;
}
Program should print only two students. This doesn't print anything because I made a mistake in accessing array grades elements. Could you help me fix this?
CodePudding user response:
When you calculate the average, you're only taking a single grade and dividing it by the number of grades. You need to add up the grades first.
void print_average(struct Student students[], int n, double avarage) {
double avarage_grade;
int i, j;
for (i = 0; i < n; i ) {
for (j=0, avarage_grade=0; j<students[i].number_of_grades; j ) {
avarage_grade = students[i].grades[j];
}
avarage_grade /= students[i].number_of_grades;
if (avarage_grade >= avarage)
printf("%s %s\n", students[i].surname, students[i].name);
}
}