Write a program that defines a(n):
- person type (first name, last name, pointers to a father and a mother person)
- function that displays the information of a person
Write a main function to test your functions.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person {
char familyname[16];
char firstname[16];
struct person *father;
struct person *mother;
};
typedef struct person person;
void display_person(person *p)
{
printf("My name is %s %s", p->firstname, p->familyname);
if ( p->father != NULL )
printf(", my father: %s %s", p->father->firstname, p->father->familyname);
if ( p->mother != NULL )
printf(", my mother: %s %s", p->mother->firstname, p->mother->familyname);
printf("\n");
}
void main() {
person *p;
person* people[1024];
int i;
p = (person *)malloc(sizeof(person));
strcpy(p->familyname, "Yaacoub");
strcpy(p->firstname, "Jacques");
p->father = NULL;
p->mother = NULL;
people[0] = p;
p = (person *)malloc(sizeof(person));
strcpy(p->familyname, "Macca");
strcpy(p->firstname, "Jacqueline");
p->father = NULL;
p->mother = NULL;
people[1] = p;
p = (person *)malloc(sizeof(person));
strcpy(p->familyname, "Yaacoub");
strcpy(p->firstname, "Antoun");
p->father = people[0];
p->mother = people[1];
people[2] = p;
for ( i=0; i<3; i++ )
display_person(people[i]);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Recursively reverse a stack