/* Name: ex5-9.c Purpose: Compares two dates: which one is earlier? Author: Bill Slough Note: datecmp is patterned on C's string comparison function */ #include int datecmp(int thisMonth, int thisDay, int thisYear, int thatMonth, int thatDay, int thatYear); int main() { int month1, day1, year1; /* first date */ int month2, day2, year2; /* second date */ /* Get the first date */ printf("Enter first date (mm/dd/yy): "); scanf("%d/%d/%d", &month1, &day1, &year1); /* Get the second date */ printf("Enter the second date (mm/dd/yy): "); scanf("%d/%d/%d", &month2, &day2, &year2); /* Compare dates and announce the outcome */ switch (datecmp(month1, day1, year1, month2, day2, year2)) { case -1: printf("%d/%d/%2.2d is earlier than %d/%d/%2.2d\n", month1, day1, year1, month2, day2, year2); break; case 0: printf("These are identical dates.\n"); break; case +1: printf("%d/%d/%2.2d is earlier than %d/%d/%2.2d\n", month2, day2, year2, month1, day1, year1); break; } return 0; } int datecmp(int thisMonth, int thisDay, int thisYear, int thatMonth, int thatDay, int thatYear) { /* Compare two dates: Given: thisMonth/thisDay/thisYear vs. thatMonth/thatDay/thatYear Result: -1 if this date < that date 0 if this date = that date +1 if this date > that date */ /* Nothing is known about the dates yet */ if (thisYear < thatYear) return -1; else if (thisYear > thatYear) return +1; /* Dates are in the same year */ if (thisMonth < thatMonth) return -1; else if (thisMonth > thatMonth) return +1; /* Dates are in the same year and month */ if (thisDay < thatDay) return -1; else if (thisDay == thatDay) return 0; else return +1; }