From 00814fe8d3de822d9042e035fd1fc367d771b2c8 Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Mon, 20 Jun 2022 14:17:29 +0530 Subject: 5.8 --- 5.8.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 5.8.c (limited to '5.8.c') diff --git a/5.8.c b/5.8.c new file mode 100644 index 0000000..03a5ebd --- /dev/null +++ b/5.8.c @@ -0,0 +1,63 @@ +#include + +#define LEAP_YEAR_DAYS 366 +#define NON_LEAP_YEAR_DAYS 365 +#define NO_OF_MONTHS 12 + +int year_day(int day, int month, int year); +void month_day(int *day, int *month, int year, int year_day_val); + +int +main(void) +{ + int day, month, year, year_day_val; + + year = 2020; + printf("yd: %d\n", (year_day_val = year_day(15, 2, year))); + + month_day(&day, &month, year, year_day_val); + printf("md: %d-%d\n", day, month); +} + +static char daytab[][12] = { + {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, + {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, +}; + +int +year_day(int day, int month, int year) +{ + int i, leap; + + leap = ((!year%4 && year%100 ) || !year%400); + + if (month > NO_OF_MONTHS || day > daytab[leap][month-1]) + return -1; + + for (i = 0, --month; i < month; i++) + day += daytab[leap][i]; + + return day; +} + +void +month_day(int *day, int *month, int year, int year_day_val) +{ + int i, leap; + + leap = ((!year%4 && year%100 ) || !year%400); + + if ((leap && year_day_val > LEAP_YEAR_DAYS) || (!leap && year_day_val > NON_LEAP_YEAR_DAYS)) { + *month = -1; + *day = -1; + return; + } + + for (i = 1; year_day_val > daytab[leap][i-1]; i++) + year_day_val -= daytab[leap][i-1]; + + *month = i; + *day = year_day_val; + + return; +} -- cgit v1.2.3