Date Comparator
C
Easy
3 views
Problem Description
Create a date structure (day, month, year). Input two dates and decide which one is first. Handle edge cases: leap year, invalid dates, odd dates
Official Solution
#include <stdio.h>
// Date structure
struct Date {
int day;
int month;
int year;
};
// Function to check leap year
int isLeapYear(int year) {
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
return 1;
return 0;
}
// Function to validate date
int isValidDate(struct Date d) {
int daysInMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
if (d.year < 1)
return 0;
if (d.month < 1 || d.month > 12)
return 0;
if (isLeapYear(d.year))
daysInMonth[2] = 29;
if (d.day < 1 || d.day > daysInMonth[d.month])
return 0;
return 1;
}
// Function to compare two dates
int compareDates(struct Date d1, struct Date d2) {
if (d1.year != d2.year)
return d1.year < d2.year;
if (d1.month != d2.month)
return d1.month < d2.month;
return d1.day < d2.day;
}
int main() {
struct Date d1, d2;
printf("Enter first date (DD MM YYYY): ");
scanf("%d %d %d", &d1.day, &d1.month, &d1.year);
printf("Enter second date (DD MM YYYY): ");
scanf("%d %d %d", &d2.day, &d2.month, &d2.year);
// Validate dates
if (!isValidDate(d1) || !isValidDate(d2)) {
printf("nInvalid date entered.n");
return 0;
}
// Compare dates
if (compareDates(d1, d2))
printf("nFirst date comes before second date.n");
else if (compareDates(d2, d1))
printf("nSecond date comes before first date.n");
else
printf("nBoth dates are the same.n");
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!