Complementary task for topic: 5

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

Structs: Define a struct array

Structs: Define a struct array

Create an array of students called Friends, that should contain Harry Potter, Ronald Weasley, Hermione Granger. Go through this array and print everyone's name separaqted by newline!

Hint: As it was mentioned struct Student is a type, so you can easily create an array of it. E.g.:
struct Student Friends[3]; will create an array of 3 students. As with other types, the initialization is not done, so you need to initialize every element befor use. However you can do it more simple:
struct Student Friends[3]={{"Harry Potter",12,55...},{"Ronald Weasly"...},{...}} like in the solution.

Solution
#include 

struct Student {
    char name[100];//Max. 99 chars for a name!
    int age;
    float magic_attack;
    float magic_defense, cleverness;
    char house[30]; //will be enum soon
};

int main() {
struct Student Friends[3]={{"Harry Potter",12,55,70,35,"Griffindor"},{"Ronald Weasley",12,57,40,55,"Griffindor"},{"Hermione Granger",13,51,60,75,"Griffindor"}};
for(int i=0;i<3;i++){
    printf("%s\n",Friends[i].name);
}
return 0;
}


Explanation
The funny thing that in this way the struct student variables has no name, they exists only in the array! Otherwise the program defines an array of Students with 3 elements
Initializes
We go through in the array and print out the names. In the next example we will use the typeset and enum to be more readable
< < previous    next > >