Consider, you need three bits of info to do your calendar, beyond the given year and month.
You need to figure the day of the week and the number of days for the month. For the number of days in the month, you need to know if it's a leap year or not.
It's no real secret, I found this on the very first page of a google search:
http://c-faq.com/misc/zeller.htmlOk, IsLeapYear should return boolean for maximum ease of use. So:
CODE
bool IsLeapYear(const int year) {
return ((year%400==0) || (year%4==0 && year%100!=0));
}
Now that we have a working IsLeapYear, time for a GetDaysInMonth, something like this:
CODE
int GetDaysInMonth (const int year, const int month) {
switch (month) {
case 2:
return IsLeapYear(year) ? 29 : 28;
case 4:
case 6:
case 9:
case 11: return 30;
default: return 31;
}
}
Now all we need is day of week, from the link:
CODE
int GetDayOfWeek(const int year, const int month) { /* 0 = Sunday */
const int d = 1;
int y = year - (month < 3);
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
return (y + y/4 - y/100 + y/400 + t[month-1] + d) % 7;
}
That's it, you're done!
Well, I guess we've made it this far... here's the rest, enjoy.
CODE
void ShowCal(const int year, const int month) {
string monthName[] = {"January","February","March","April","May","June","July",
"August","September","October","November","December"};
int days = GetDaysInMonth(year, month);
int dow = GetDayOfWeek(year, month);
cout << monthName[month-1] << endl;
cout << " Sun Mon Tue Wed Thu Fri Sat" << endl;
cout << " --- --- --- --- --- --- ---" << endl << " ";
for(int day=0; day<dow; day++) { cout << " "; }
for(int day=1; day<=days; day++) {
cout << setw(3) << day << " ";
if (++dow>6) { dow = 0; cout << endl << " "; }
}
cout << endl;
}
This post has been edited by baavgai: 6 Dec, 2007 - 06:27 PM