Consider the problem of comparison of two valid dates d1 and d2. There are three possible outcomes of this comparison: d1 == d2 (dates are equal), d1 > d2 (date d1 is greater, i.e., occurs after d2) and d1 < d2(date d1 is smaller, i.e., occurs before d2). Let us write a function that accepts two dates as structures dl and d2 of type struct date and returns 0 if the dates are equal, 1 if d1 is later than d2 and -1 if date dl is earlier than d2.
The given dates are equal if all the components (dd, mm and yy) of two dates are equal. Also, date dl is greater if any one of the following conditions is satisfied:
1. d1.yy > d2.yy, 2. d1.yy == d2.yy and d1.mm > d2.mm, 3. d1.yy == d2.yy and d1.mm == d2.mm and d1.dd > d2.dd
A complete program that uses the date_cmp function to compare two given dates using an if else-if statement and prints the appropriate message in the main function is given below.
/* compare two dates and print appropriate message */ #include<stdio.h> struct date { int dd, mm, yy; }; int date_cmp(struct date d1, struct date d2); void date_print(struct date d); int main() { struct date d1 = {7, 3, 2005}; struct date d2 = {24, 10, 2005}; date_print(d1); int cmp = date_cmp(d1, d2); if(cmp == 0) printf(" is equal to"); else if (cmp > 0) printf(" is greater i.e. later than "); else printf(" is smaller i.e. earlier than"); date_print(d2); return 0; } /* compare given dates d1 and d2 */ int date_cmp(struct date d1, struct date d2) { if (d1.dd == d2.dd && d1.mm == d2.mm && d1.yy ==d2.yy) return 0; else if (d1.yy > d2.yy || d1.yy == d2.yy && d1.mm > d2.mm || d1.yy == d2.yy && d1.mm == d2.mm && d1.dd > d2.dd) return 1; else return -1; } /* print a given date */ void date_print(struct date d) { printf("%d/%d/%d", d.dd, d.mm, d.yy); }
The program output is given below.
7/3/2005 is smaller i.e. earlier than 24/10/2005