/* Name: ex6-10.c Purpose: Find the earliest date in a sequence of dates Author: Bill Slough Notes: datecmp is identical to the function we used for ex5-9 dates are processed using a "loop and a half" user is expected to enter 0/0/0 to terminate input */ #include #define TRUE 1 int datecmp(int thisMonth, int thisDay, int thisYear, int thatMonth, int thatDay, int thatYear); int main() { int earliestMonth = 12; int earliestDay = 31; int earliestYear = 99; /* "infinity" date */ int month, day, year; /* next date to process */ int count = 0; /* number of dates processed */ while (TRUE) { /* get the next date */ printf("Enter a date (mm/dd/yy): "); scanf("%d/%d/%d", &month, &day, &year); /* terminate loop if this is the sentinel date */ if (month == 0 && day == 0 && year == 0) break; /* process this date */ count++; if (datecmp(month, day, year, earliestMonth, earliestDay, earliestYear) == -1) { /* this date is the earliest seen so far */ earliestMonth = month; earliestDay = day; earliestYear = year; } } /* Display the result */ if (count == 0) printf("No dates were entered!\n"); else printf("%d/%d/%2.2d is the earliest date\n", earliestMonth, earliestDay, earliestYear); 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; }