64 747
Assignments Done
99,3%
Successfully Done
In September 2018

Answer to Question #52788 in C for raghu

Question #52788
Write a program that prompts the user to enter two dates and then find which date comes earlier on the calendar. Use structure to store date and function to compare dates.
Sample Run:
Enter first date (mm/dd/yy) : 3/8/10
Enter second date (mm/dd/yy) : 5/17/11
3/8/10 is earlier than 5/17/11.
Expert's answer
#include <stdio.h>
#include <stdlib.h>
struct date
{
int month;
int day;
int year;
};
void printDate(const date *date)
{
printf("%d/%d/%d", date->month, date->day, date->year);
}
int compareDates(const date *first, const date *second)
{
int firstIsGreater = 0; // 0 - is not greater, 1 - is greater, 2 - are equals
if (first->year > second->year)
{
firstIsGreater = 1;
}
else if (first->year == second->year && first->month > second->month)
{
firstIsGreater = 1;
}
else if (first->year == second->year && first->month == second->month && first->day > second->day)
{
firstIsGreater = 1;
}
else if (first->year == second->year && first->month == second->month && first->day == second->day)
{
firstIsGreater = 2;
}
return firstIsGreater;
}
int main()
{
char firstDate[10];
char secondDate[10];
printf("Enter first date (mm/dd/yy): ");
gets(firstDate);
printf("Enter second date (mm/dd/yy): ");
gets(secondDate);
date first, second;

int index = -1;
int current = 0;
int type = 0; // 0 - month, 1 - day, 2 - year
do
{
index++;
if (firstDate[index] == '/' || firstDate[index] == '\0')
{
switch (type)
{
case 0:
first.month = current;
break;
case 1:
first.day = current;
break;
case 2:
first.year = current;
break;
}
type++;
current = 0;
}
else if (!current)
{
current = atoi(&firstDate;[index]);
}
} while (firstDate[index] != '\0');
index = -1;
type = 0;
current = 0;
do
{
index++;
if (secondDate[index] == '/' || secondDate[index] == '\0')
{
switch (type)
{
case 0:
second.month = current;
break;
case 1:
second.day = current;
break;
case 2:
second.year = current;
break;
}
type++;
current = 0;
}
else if (!current)
{
current = atoi(&secondDate;[index]);
}
} while (secondDate[index] != '\0');
int answer = compareDates(&first;, &second;);
switch(answer)
{
case 0:
printDate(&first;);
printf(" is earlier than ");
printDate(&second;);
break;
case 1:
printDate(&first;);
printf(" is not earlier than ");
printDate(&second;);
break;
case 2:
printDate(&first;);
printf(" is equal to ");
printDate(&second;);
break;
}
return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions