Complementary task for topic: 5
M Nemeth · 2023-08-29 15:21:04.620218'
Structs: Define a struct
Structs: Define a struct
In the next few examples we will create a datbase of the students of Hogwarts. Our goal is to be able to search for a student, or make satistics. At the end we will create a Duel() function, that results in a winner of a magig duel.
The first task is to create a structure to store the students data (name, age, magic attack, magic defense, cleverness, house)
First we will use the house as a string, but it is really an enum (will be changed)
Task is to define the structure, create a student called Harry Potter, and print out his age.
Hint: Structs are used for bound different data types to each other. It will create a new type e.g. struct Student{int age; int magic_defense;...} will create a sturct Student type (as if it were integer or float), you can use the field with the . operator. e.g.:
struct Student HP={12,5,...};
int a=HP.age; //a will be 12
But you can write the fields with this operator as well:
HP.age=29; //HP is 17 yrs older...
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 Harry_Potter={"Harry Potter",12,55,70,35,"Griffindor"};//you can initialize as this, or using the . operator
printf("%d",Harry_Potter.age);
return 0;
}
Explanation
structure is defined, initialized and the required result is printed out. Try to print other records, e.g. house with %s!