By Rahul Sah
In this article, we are going to learn how we can print a calendar for a given year using basic C++ language.
Below function dayNumber() takes the day, month, and year as a parameter returns the start day of every month i.e returns 0-Sunday,1-Monday, and so on.
int dayNumber(int day, int month, int year) { static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1,4, 6, 2, 4 }; year -= month < 3; /*Proven formula for finding the starting day of month*/ return ( year + year/4 - year/100 + year/400 + t[month-1] + day) % 7; }
We have created a function getMonthName() which returns a string for input month number i.e, 0-January, 1-February, and so on
string getMonthName(int monthNumber) { string months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return (months[monthNumber]); }
Now, we just need to find the number of days in the month according to the year (for example, a leap year has 29 days in February month and 28 days for the normal year)
We have created a function that returns a number of days.
int numberOfDays (int monthNumber, int year) { int month[]={31,28,31,30,31,30,31,31,30,31,30,31}; if (monthNumber == 1) { /*If the year is leap then February has 29 days*/ if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) month[1]=29; } return month[monthNumber]; }
We are almost done, we just need to print the calendar. Here is the code for printing the calendar.
void printCalendar(int year) { printf ("\n\n Calendar - %d\n\n", year); int days; int current = dayNumber (1, 1, year); for (int i = 0; i < 12; i++) { days = numberOfDays (i, year); printf("\n ------------%s-%d-------------\n", getMonthName (i).c_str(),year); printf(" Sun Mon Tue Wed Thu Fri Sat\n"); int k; for (k = 0; k < current; k++) printf(" "); for (int j = 1; j <= days; j++) { printf("%5d", j); if (++k > 6) { k = 0; printf("\n"); } } if (k) printf("\n"); current = k; } }
In this way, you can print a Calendar by using C++ language. I hope it was easy enough to understand. If you have any doubt, feel free to ask in the comment section. All the best!
Thank you!
Regards,
Rahul Sah
Codespeedy Tech Pvt. Ltd.
Submitted by Rahul Sah (rahulsah1436)
Download packets of source code on Coders Packet
Comments