Complementary task for topic: 5
M Nemeth · 2023-08-29 15:21:04.622218'
Structs: Pass struct array to function
Structs: Pass struct array to function
Create best function that recieves a Student array and gives back the index of the student with maximum force!
Use the function in the main() function
Hint: The array type is Student[], or Student* (pointer, soon you will understand). when we pass an array, the size MUST be passed too!
Solution
#include
enum House{
Griffindor,
Huffelpuff,
Ravenclaw,
Slytherin
};
typedef struct Student {
char name[100];//Max. 99 chars for a name!
int age;
float magic_attack;
float magic_defense, cleverness;
enum House house; //it is an enum, must be defined before first use!
}Student;
float force(Student stud){
return stud.magic_defense+stud.magic_attack;
}
int best_student(Student Stud[], size_t size){//can be int size as well
int max_index=0;
int max_value=force(Stud[0]);//force must be declared earier!
for(int i=1;imax_value){
max_index=i;
max_value=force(Stud[i]);}
}
return max_index;
}
int main() {
Student Foes[]={{"Draco Malfoy",12,50,50,60,Slytherin},{"Gregory Goyle",13,47,50,25,Slytherin},{"Vincent Crabb",12,51,60,35,Slytherin}};
Student Friends[]={{"Harry Potter",12,55,70,35,Griffindor},{"Ronald Weasley",12,57,40,55,Griffindor},{"Hermione Granger",13,51,60,75,Griffindor}};
int max_index=best_student(Foes,3);
printf("In foes:%s with %.0f\n",Foes[max_index].name,force(Foes[max_index]));
max_index=best_student(Friends,3);
printf("In Friends:%s with %.0f\n",Friends[max_index].name,force(Friends[max_index]));
return 0;
}
Explanation
much better code... Let us move on, implement some dueling