C++ program to display the calendar
This blog creates a c++program to display the calendar. It prints a month calendar.
How to implement the program?
- First, include the built-in header files and namespace std.
- Next, check the leap year of the year.
- It checks the year is divided by 4,100 and 400, then it is leap year.
- Function daysOfMonth() assigns each month’s days value.
- For February month,check for leap year and assign the value as 29.
- Zeller’s Congruence is used to find the weekday.
- Finally, main() function gets the input as month and year and prints the calendar.
Code:
#include <iostream>
#include <iomanip>
using namespace std;
// leap year checking function
bool checkLeap(int yr) {
return (yr % 4 ==
0 && yr % 100 != 0) || (yr % 400 == 0);
}
// days of the month
int daysOfMonth(int yr, int month) {
int days[] =
{31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2
&& checkLeap(yr)) return 29;
return days[month
- 1];
}
// Function to find the weekday using Zeller’s Congruence.
Let us consider Sunday as 0.
int week_Day(int yr, int month, int day) {
if (month < 3)
{ month += 12; yr--; }
int K = yr % 100;
int J = yr / 100;
int h = (day +
(13*(month+1))/5 + K + K/4 + J/4 + 5*J) % 7;
return (h + 6) %
7; // here Sunday is assigned as 0
}
int yr, month;
cout <<
"Enter year and month (e.g.1 2026): ";
cin >> month
>> yr;
cout <<
"\n Calendar for " <<
month << "/" << yr << "\n";
cout <<
"Sun Mon Tue Wed Thu Fri Sat\n";
int fDay =
week_Day(yr, month, 1);
int tDays =
daysOfMonth(yr, month);
// Print the
leading spaces
for (int i = 0; i
< fDay; i++) cout << "
";
// Print the days
for (int d = 1; d
<= tDays; d++) {
cout <<
setw(3) << d << " ";
if ((d + fDay)
% 7 == 0) cout << "\n";
}
cout <<
"\n";
return 0;
}
Output:
Enter year and month (e.g.1 2026): 9 2026
Calendar for 9/2026
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15
16 17 18 19
20 21
22 23 24
25
26
27 28 29 30
That’s all. The c++ program to display the calendar of year
and month. Hope, this code is useful to you. Keep coding!!!
Comments
Post a Comment