Reputation: 81
Function int getMax(student *students, int entry_size) should calculate max grade among all students. student here is structure, and *students is array, entry_size already can found using function that is indicated below. Trick with getMax function is that it should use recursion; File format that contains data is as follows:
Name Surname ID Grade
Name Surname ID Grade
...
I have done part of code where it scans and returns an array of students:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char firstName[30], secondName[30];
int ID;
int grade;
} student;
typedef struct {
int ID;
int avgGrade;
} topThreeAvg;
student *readStudents(char *fileName, int* entry_size, int *all_ids, int* studentSize){
/*
all_ids is an array for counting the amount of grades per student. studentSize is the actual number of students (for example, in students1.txt it is 2)
*/
FILE *openedFile = fopen(fileName, "r");
if(openedFile == NULL){
printf("Cannot open a file");
exit (0);
}
char entrySize[10];
fscanf(openedFile, "%[^\n]", entrySize);
int numberOfEntries = atoi(entrySize);
*entry_size = numberOfEntries;
student *students;
if ( NULL == ( students = malloc(numberOfEntries * sizeof *students))) {
printf ("Error with memory allocation");
exit (0);
}
int i;
for(i=0; i < numberOfEntries; i++){
if (4 != fscanf(openedFile, "%s %s %d %d"
, students[i].firstName
, students[i].secondName
, &students[i].ID
, &students[i].grade)) {
exit (0);
}
}
return students;
}
I tried to implement the function, but it gives very huge number:
int max_in(student *students, int entry_size){
int curr_val = students->grade;
if (entry_size == 1) {
return curr_val;
}
int max_in_rest = max_in(&students->ID+1, entry_size-1);
return curr_val > max_in_rest ? curr_val : max_in_rest;
}
How to make a function recursive and find that maximum grade among all students?
Upvotes: 0
Views: 366
Reputation: 12742
Try as below.
int max(int x, int y){
return x > y ? x : y;
}
int max_in(student *students, int entry_size){
if (entry_size <= 0){
return -1;
}
else {
return max(students[entry_size-1].grade, max_in(students, entry_size-1))
}
}
Upvotes: 1