C++ Program to Check Leap Year

Source Code

#include <iostream>

using namespace std;

int main()
{
    int year; // Declare a variable to hold the year

    cout << "Enter a year: "; // Prompt the user to enter the year
    cin >> year; // Read the year from the standard input stream

    // Check if the year is a leap year
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
        cout << year << " is a leap year" << endl;
    else
        cout << year << " is not a leap year" << endl;

    return 0;
}

Code Explanation

This program declares a variable year of type int to hold the year entered by the user. It then uses the cout object to print a prompt asking the user to enter the year, and the cin object to read the year from the standard input stream.

To check if the year is a leap year, the program uses an if statement with a logical OR (||) operator to test whether the year is divisible by 400, or is divisible by 4 but not by 100. If either of these conditions is true, the year is a leap year. Otherwise, it is not a leap year.

The program then uses the cout object to print a message indicating whether the year is a leap year or not.

Explain Leap Year

A leap year is a year that is divisible by 4, except for years that are both divisible by 100 and not divisible by 400. For example, the year 2000 was a leap year because it was divisible by 400, but 1900 was not a leap year because it was divisible by 100 but not by 400.

Leap years are necessary to keep the calendar in sync with the Earth’s orbit around the Sun. The Earth’s orbit around the Sun is not exactly 365 days, but is slightly longer. To account for this extra time, a leap year has 366 days instead of 365. The extra day is added to the month of February, which has 29 days in a leap year instead of 28.

A simple year is a year that is not a leap year, that is, a year that has 365 days. Simple years are those that are not divisible by 4, or are divisible by 100 but not by 400.

For example, the following years are leap years:

  • 2004
  • 2008
  • 2012
  • 2016
  • 2020

The following years are simple years:

  • 2001
  • 2002
  • 2003
  • 2005
  • 2006