Alternative solution by Jesse Weinstein; let me know if it seems worth posting on the main page and/or any corrections. -- JesseW 06:44, 19 July 2007 (BST)
/* alternative solution to K&R exercise 5.9, demonstrating method of addressing a 2 dimensional array with pointers. Put together by Jesse Weinstein, based on code as listed below. Wed Jul 18 22:45:08 2007 */ #include <stdio.h> /* based off of code in K&R, p. 111 */ /* exercise is to use pointers, not indexes */ static char daytab[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; /*day_of_year: return day of year from year, month and day */ int day_of_year(int year, int month, int day) { int i, leap; if (month > 12) return -1; /* error */ leap = year%4 == 0 && year%100 != 0 || year%400 == 0; for ( i = 1; i < month; i++) day += *(*(daytab+leap)+i); return day; } /* month_day: set month, day from year, and yearday */ int month_day(int year, int yearday, int *pmonth, int *pday) { int i, leap; leap = year%4 == 0 && year%100 != 0 || year%400 == 0; for (i = 1; i < 13 && yearday > *(*(daytab+leap)+i); i++) yearday -= *(*(daytab+leap)+i); *pmonth = i; *pday = yearday; return 0; } /* main: test day_of_year and month_day */ /* copied from Lars Wirzenius's solution to K&R exercise 5.8 available at: http://www.clc-wiki.net/mediawiki/index.php?title=K%26R2_solutions:Chapter_5:Exercise_8&oldid=3971 */ int main(void) { int year, month, day, yearday; for (year = 1970; year <= 2000; ++year) { for (yearday = 1; yearday < 366; ++yearday) { if (month_day(year, yearday, &month, &day) == -1) { printf("month_day failed: %d %d\n", year, yearday); } else if (day_of_year(year, month, day) != yearday) { printf("bad result: %d %d\n", year, yearday); printf("month = %d, day = %d\n", month, day); } } } return 0; }