Complementary task for topic: 5
M Nemeth · 2023-08-29 15:21:04.622218'
Structs: Pass struct to function
Structs: Pass struct to function
Create force function that recieves a student and gives back the sum of the magic_attack and magic_defense.
Use the function in the main() function
Hint: The Student is a types use it accordingly.
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 main() {
Student Foes[3]={{"Draco Malfoy",12,50,50,60,Slytherin},{"Gregory Goyle",13,47,50,25,Slytherin},{"Vincent Crabb",12,51,60,35,Slytherin}};
Student Friends[3]={{"Harry Potter",12,55,70,35,Griffindor},{"Ronald Weasley",12,57,40,55,Griffindor},{"Hermione Granger",13,51,60,75,Griffindor}};
int max_index=0;
int max_value=force(Foes[0]);
for(int i=1;i<3;i++){
if(force(Foes[i])>max_value){
max_index=i;
max_value=force(Foes[i]);}
}
printf("In foes:%s with %.0f\n",Foes[max_index].name,force(Foes[max_index]));
max_index=0;
max_value=force(Friends[0]);
for(int i=1;i<3;i++){
if(force(Friends[i])>max_value){
max_index=i;
max_value=force(Friends[i]);}
}
printf("In Friends:%s with %.0f\n",Friends[max_index].name,force(Friends[max_index]));
return 0;
}
Explanation
Student type object easily passed to a function, where we can use as usual. That looks better, but could we pass a struct array to a function? It would be nice to write a maximum search only once!