/* * Program that finds Julian date for given month, day, year. * * Prompts for month, day, year. */ #include #include #include int jdate(char *mname, int day, bool is_leap); int main(int argc, char *argv[]) { char mname[4]; int day, year; puts("enter month (3 char) day year"); if (scanf("%3s %d %d", mname, &day, &year) != 3) { puts("invalid input"); return 1; } if ((year < 1) || (day < 1)) { puts("invalid input"); return 1; } bool is_leapyear = ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))); /* * compute julian day and then echo input, followed by * "invalid input" or converted day */ int jday = jdate(mname, day, is_leapyear); printf("%s %d %d (%s) ", /* print this for both valid/invalid input */ mname, day, year, (is_leapyear) ? "a leapyear" : "not a leapyear"); if (jday == -1) { puts("is invalid"); return 1; } else { printf("is Julian date %d\n", jday); return 0; } } /* type for table of entries, one per month */ typedef struct { char *mname; int days_in_month; int extra_days_for_leapyear; } month_and_days_t; /* return julian day, or -1 if input is invalid */ int jdate(char *mname, int day, bool is_leap) { month_and_days_t cal[] = { { "Jan", 31, 0 }, { "Feb", 28, 1 }, { "Mar", 31, 0 }, { "Apr", 30, 0 }, { "May", 31, 0 }, { "Jun", 30, 0 }, { "Jul", 31, 0 }, { "Aug", 31, 0 }, { "Sep", 30, 0 }, { "Oct", 31, 0 }, { "Nov", 30, 0 }, { "Dec", 31, 0 } }; int days_prev = 0; /* days in previous months */ for (int i = 0; i < 12; ++i) { if (strcmp(mname, cal[i].mname) == 0) { if (day > cal[i].days_in_month) { return -1; } return days_prev + day; } else { days_prev += cal[i].days_in_month; if (is_leap) days_prev += cal[i].extra_days_for_leapyear; } } return -1; }