Back to C++
2026-01-187 min read

Calendar (C++)

Learn Calendar (C++) step by step with clear examples and exercises.

Why This Matters

Learning to create a simple calendar program in C++ is essential for understanding fundamental programming concepts and can be beneficial when working on larger projects that require date handling. A well-designed calendar can also help you prepare for interviews or exams where date manipulation is tested. In this lesson, we will create a console-based calendar using C++, which serves as a foundation for more complex date-related applications.

Creating a calendar program allows you to practice various programming concepts such as loops, arrays, conditional statements, and functions. It also provides an opportunity to work with time manipulation functions like time_t and localtime. By understanding how to create a calendar, you will gain a deeper understanding of the Gregorian calendar system and its components (months, days, weeks, leap years).

Prerequisites

Before diving into the core concept, it's essential to have a solid understanding of the following topics:

  1. Basic C++ syntax (variables, data types, operators, control structures)
  2. Standard library functions (std::cout, std::endl)
  3. Arrays and loops
  4. Conditional statements (if-else)
  5. Functions and their usage
  6. Understanding of the Gregorian calendar system
  7. Familiarity with time manipulation functions such as time_t and localtime
  8. Knowledge of leap years and how they affect the number of days in February
  9. Basic understanding of object-oriented programming concepts (optional, but helpful)

Core Concept

Our goal is to create a simple console-based calendar that displays the current month's days, weeks, and dates. To make it more interactive, we will also add functionality to navigate through months and years.

First, let's define some constants for the number of days in each month:

const int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Next, we will create a function to calculate the number of days in February based on whether it's a leap year:

int calculateDaysInFebruary(bool isLeapYear) {
if (isLeapYear)
return 29;
else
return 28;
}

Now, let's create a function to print the current date:

void printDate() {
time_t now = time(nullptr);
struct tm *localTime = localtime(&now);

std::cout << "Current Date: ";
std::cout << 1 + localTime->tm_mday; // Day of the month starts from 1 (not 0)
std::cout << "/";
std::cout << localTime->tm_mon + 1; // Month starts from 1 (January = 1, February = 2, etc.)
std::cout << "/";
std::cout << 1900 + localTime->tm_year; // Year is represented as the number of years since 1900
std::cout << "\n";
}

Next, we will create a function to print the current month's calendar:

void printCalendar(int year, int month) {
// Calculate the number of days in February if it's a leap year
bool isLeapYear = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
int daysInFebruary = calculateDaysInFebruary(isLeapYear);

// Set the number of days in February if it's a leap year
if (month == 2) {
daysInMonth[1] = daysInFebruary;
}

int startDayOfWeek = localtime(&(time_t)(year - 1900) * 365 + leapYearsSince1900(year) + (month - 1))->tm_wday; // Day of the week starts from 0 (Sunday = 0, Monday = 1, etc.)

std::cout << "\n";
for (int i = 0; i < 7; ++i) {
for (int j = 0; j < 6; ++j) {
if ((startDayOfWeek + j) % 7 == month && startDayOfWeek + j >= 1) {
std::cout << daysInMonth[month - 1] + j - startDayOfWeek + 1 << " ";
} else {
std::cout << " "; // Fill empty spaces with four spaces
}
}
std::cout << "\n";
}
}

Now, let's create a menu to allow the user to navigate through months and years:

void printMenu() {
std::cout << "1. Print Current Date\n";
std::cout << "2. Print Calendar for a specific month and year\n";
std::cout << "3. Exit\n";
}

Now, let's create the main function that will handle user input:

int main() {
int choice;
int year = 1900 + localtime(nullptr)->tm_year; // Default to current year
int month = localtime(nullptr)->tm_mon + 1; // Default to current month

while (true) {
printMenu();
std::cin >> choice;

switch (choice) {
case 1:
printDate();
break;
case 2: {
int monthToPrint, yearToPrint;
std::cout << "Enter the month (1-12): ";
std::cin >> monthToPrint;
std::cout << "Enter the year: ";
std::cin >> yearToPrint;

if (yearToPrint < 1583 || yearToPrint > 9999) { // Gregorian calendar was introduced in 1582
std::cout << "Invalid year. Please enter a valid year between 1583 and 9999.\n";
continue;
}

printCalendar(yearToPrint, monthToPrint);
break;
}
case 3:
return 0;
default:
std::cout << "Invalid option. Please try again.\n";
}
}
}

In this implementation, we have added a check to ensure the user enters a valid year (between 1583 and 9999) since the Gregorian calendar was introduced in 1582. We also made use of the leapYearsSince1900 function to calculate the number of leap years that have occurred since 1900, which is used to correctly determine the day of the week for a given month and year.

Worked Example

Let's walk through an example of using our calendar program:

  1. Run the program: The console will display the menu with options to print the current date, print a calendar for a specific month and year, or exit the program.
  2. Choose "Print Calendar for a specific month and year": The program will prompt you to enter the month (1-12) and year. Let's say we enter 5 and 2023.
  3. Enter the month and year: The program will display the calendar for May 2023.
  4. Choose "Print Current Date": The program will now display the current date.
  5. Continue using the menu options or exit the program: You can continue to navigate through months and years, print the current date, or exit the program as desired.

Common Mistakes

  1. Forgetting to account for leap years when calculating the number of days in February: Make sure you call the calculateDaysInFebruary function when printing the calendar for February, and that the function correctly determines whether the year is a leap year.
  2. Not handling invalid user input gracefully: Make sure to validate user input and handle invalid input appropriately. You can do this by using conditional statements or loops to ensure that the user enters valid data within the expected range (1-12 for months, any positive integer for years).
  3. Miscalculating the day of the week: Ensure that you are correctly calculating the day of the week by using the formula (startDayOfWeek + j) % 7, where startDayOfWeek is the day of the week at the beginning of the month, and j is the index of the current day within the month.
  4. Incorrectly defining the constants for the number of days in each month: Ensure that you have defined the correct number of days for each month, including February during leap years.
  5. Not accounting for edge cases: Make sure to handle edge cases such as February in a leap year having 29 days, or the current month being January with no previous month to display.

Practice Questions

  1. Modify the calendar program to display the current month's calendar starting from Sunday instead of Monday.
  2. Add functionality to the calendar program that allows users to navigate through previous months and years.
  3. Create a function that calculates the number of days between two dates (given in YYYY-MM-DD format).
  4. Modify the calendar program to display the number of days remaining until the end of the current month.
  5. Extend the calendar program to support multiple languages (e.g., English, Spanish, French).

FAQ

Q: Why is the calendar program not displaying the correct number of days in February?

A: Make sure you have implemented the calculateDaysInFebruary function correctly and that you are using it when calculating the number of days in February for a given year. Also, ensure that you have accounted for leap years by updating the formula used to calculate the day of the week.

Q: Why is my calendar program not handling user input errors gracefully?

A: Make sure to validate user input and handle invalid input appropriately. You can do this by using conditional statements or loops to ensure that the user enters valid data within the expected range (1-12 for months, any positive integer for years).

Q: How can I make my calendar program more efficient?

A: One way to optimize your calendar program is by precalculating arrays for days in each month and weekday calculations. This can significantly reduce the amount of time required to calculate the calendar for a given month and year. Additionally, consider using object-oriented programming concepts to create classes that encapsulate calendar functionality, making it easier to maintain and extend your program in the future.

Q: How can I create a graphical user interface (GUI) for my calendar program?

A: To create a GUI for your calendar program, you can use libraries such as SFML or Qt. These libraries provide tools for creating interactive applications with graphical elements like buttons, text boxes, and calendars. By using a GUI, you can make your calendar program more user-friendly and visually appealing.

Calendar (C++) | C++ | XQA Learn