Suppose you have 12 passengers on a ship. Each of them is different. These 12 passengers are divided into the categories of:
- class
- age
- gender
Each of these categories can have 2 different options:
class is either "first" or "second"
age is either "adult" or "child"
gender is either "male" or "female"
I decided to create a new datatype of type struct called "Passenger". As you will see in the code below, it has three members: class, age, gender.
And then I create a variable (allPassengers) of this newly created datatype (Passenger).
But now, how do I fill out the array of type Passenger called "allPassengers" with the all 12 different combinations of info about Passengers?
E.g. I created manually the first three combinations:
#include < stdio.h > #include < string.h >
typedef struct {
char class[7];
char age[6];
char gender[7];
}
Passenger;
/* This is where all the information about passengers will be stored, global variable,
there are 9 combinations of passengers (allocated array elements for the variable), last one is reserved for the null character \0 */
Passenger allPassengers[10];
int main() {
// First combination
strcpy(allPassengers[0].class, "first");
strcpy(allPassengers[0].age, "adult");
strcpy(allPassengers[0].gender, "male");
// Second combination
strcpy(allPassengers[1].class, "second");
strcpy(allPassengers[1].age, "adult");
strcpy(allPassengers[1].gender, "male");
// Third combination
strcpy(allPassengers[2].class, "first");
strcpy(allPassengers[2].age, "child");
strcpy(allPassengers[2].gender, "male");
// ... etc
return 0;
}
Here's the same code (copy-paste friendly).
I know it'd have been easy to fill out an array with just numbers (for loops). But I have no idea how to fill out, for example, the first two allPassengers[0]
, and allPassengers[1]
with necessary information. I guess I'd write a complex "if statements" inside for loops e.g. check the class of the previous allPassengers e.g. if there are more than 2 matches, assign class "second".
Or switch case... dunno. What if I had to fill out a harder combination.
How do I only allow a limited strings for the variable to take? e.g. class can take either "first" or "second"?
Any clues?