In: Computer Science
Written in C code:
Using a structure called person, write a C function called compare_age that takes two person structure pointers as input and returns 1 if the first person is older, -1 if the second person is older, or 0 if they have exactly the same birthday. Hint: Compare the years first, then if equal compare months, if they are equal compare days.
The structure called person should contain the following; has fields for name (50 char array), dateOfBirth (structure called date that has three fields day, month, year, all of which are ints.), address (200 char array), phoneNum (20 char array), and ID (int).
You should print out the comparison result of whether person 1 or 2 is older or if they have the same age.
#include<stdio.h>
struct date
{
int day;
int month;
int year;
};
struct person
{
char name[50];
struct date dateOfBirth;
char address[200];
char phoneNum[20];
int ID;
};
int compare_age(struct person *person1,struct person
*person2)
{
if(person1->dateOfBirth.year==person2->dateOfBirth.year)
{
if(person1->dateOfBirth.month==person2->dateOfBirth.month)
{
if(person1->dateOfBirth.day==person2->dateOfBirth.day)
return 0;
else
if(person1->dateOfBirth.day<person2->dateOfBirth.day)
return 1;
else
return -1;
}
else
if(person1->dateOfBirth.month<person2->dateOfBirth.month)
return 1;
else
return -1;
}
else
if(person1->dateOfBirth.year<person2->dateOfBirth.year)
return 1;
else
return -1;
}
void main()
{
struct person person1,person2;
printf("person1 details\n");
printf("Enter name: ");
scanf("%s",person1.name);
printf("Date of Birth details: \n");
printf("Enter day: ");
scanf("%d",&person1.dateOfBirth.day);
printf("Enter month: ");
scanf("%d",&person1.dateOfBirth.month);
printf("Enter year: ");
scanf("%d",&person1.dateOfBirth.year);
printf("Enter address: ");
scanf("%s",person1.address);
printf("Enter phone number: ");
scanf("%s",person1.phoneNum);
printf("Enter ID: ");
scanf("%d",&person1.ID);
printf("person2 details\n");
printf("Enter name: ");
scanf("%s",person2.name);
printf("Date of Birth details: \n");
printf("Enter day: ");
scanf("%d",&person2.dateOfBirth.day);
printf("Enter month: ");
scanf("%d",&person2.dateOfBirth.month);
printf("Enter year: ");
scanf("%d",&person2.dateOfBirth.year);
printf("Enter address: ");
scanf("%s",person2.address);
printf("Enter phone number: ");
scanf("%s",person2.phoneNum);
printf("Enter ID: ");
scanf("%d",&person2.ID);
if(compare_age(&person1,&person2)>0)
printf("person1 is older\n");
else if(compare_age(&person1,&person2)<0)
printf("person2 is older\n");
else
printf("person1 and person2 have same age\n");
}
Output