Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

5.5. Determining a Day’s Number Within a Given Year

Problem

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.

Solution

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) ? ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page