Complementary task for topic: 5

M Nemeth · 2023-08-29 15:21:04.621219'

Structs: Search in array

Structs: Search in array

Create one more array of Foes with Draco Malfoy, Gregory Goyle and Vincent Crabbe. Find the strongest in magic attact+magic deffense in both gang, print out the bests

Hint: We need to search in both arrays. The indexes should be stored to get the name!

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;

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=Foes[0].magic_attack+Foes[0].magic_defense;

for(int i=1;i<3;i++){
    if(Foes[i].magic_attack+Foes[i].magic_defense>max_value){
	max_index=i;
	max_value=Foes[i].magic_attack+Foes[i].magic_defense;}
}
printf("In foes:%s with %.0f\n",Foes[max_index].name,Foes[max_index].magic_attack+Foes[max_index].magic_defense);

max_index=0;
max_value=Friends[0].magic_attack+Friends[0].magic_defense;

for(int i=1;i<3;i++){
    if(Friends[i].magic_attack+Friends[i].magic_defense>max_value){
	max_index=i;
	max_value=Friends[i].magic_attack+Friends[i].magic_defense;}
}
printf("In Friends:%s with %.0f\n",Friends[max_index].name,Friends[max_index].magic_attack+Friends[max_index].magic_defense);

return 0;
}


Explanation
See the code above, it starts to stink... What does it mean? That we do the same things multiple times by hand. It is very hard to maintain (e.g. if somewhere there is a mistake, there will be next time as well, because we copy-pasted the code parts). In situations like this a re-organization is necessary. E.g.: we calculated the force (sum of magical_attack and defense) multiple times, for printf() we could use the max_value as well. That should be a function. The maximum search could be a function as well. Next tasks are about these functions
< < previous    next > >