November 2005
Beginner to intermediate
594 pages
16h 23m
English
You want to determine a day’s number within a given year. For example, January 1 is the first day of each year; February 5 is the 36th day of each year, and so on. But since some years have leap days, after February 28, a given day doesn’t necessarily have the same numbering each year.
The solution to this problem requires the solution to several problems simultaneously. First, you have to know how many days are in each month, which, in turn, means you have to know how to determine whether a year is a leap year. Example 5-9 provides routines for performing these computations.
Example 5-9. Routines for determining a day’s number within a given year
#include <iostream> using namespace std; enum MonthEnum { jan = 0, feb = 1, mar = 2, apr = 3, may = 4, jun = 5, jul = 6, aug = 7, sep = 8, oct = 9, nov = 10, dec = 11 }; bool isLeapYear(int y) { return (y % 4 == 0) && ((y % 100 != 0) || (y % 400 == 0)); } const int arrayDaysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int n; int arrayFirstOfMonth[] = { n = 0, n += arrayDaysInMonth[jan], n += arrayDaysInMonth[feb], n += arrayDaysInMonth[mar], n += arrayDaysInMonth[apr], n += arrayDaysInMonth[may], n += arrayDaysInMonth[jun], n += arrayDaysInMonth[jul], n += arrayDaysInMonth[aug], n += arrayDaysInMonth[sep], n += arrayDaysInMonth[::oct], n += arrayDaysInMonth[nov] }; int daysInMonth(MonthEnum month, int year) { if (month == feb) { return isLeapYear(year) ? ...