C++ Program to check Leap Year

Write a C++ Program to take a year as input from the user and determine whether it is a leap year. 
A leap year is defined as a year that is divisible by 4 but not by 100 unless it is also divisible by 400. This rule accounts for the extra day in February.

Input and Output Examples

  • Input: 2020

    Output: 2020 is a leap year.

  • Input: 2019

    Output: 2019 is not a leap year.

Algorithm to Check Leap Year

  1. Start the program.
  2. Prompt the user to enter a year.
  3. Read the year from user input.
  4. Check if the year is divisible by 4 but not by 100, or if it is divisible by 400.
  5. If the conditions are met, display that the year is a leap year.
  6. If the conditions are not met, display that the year is not a leap year.
  7. End the program.

Below is the C++ code to determine if a year is a leap year:

cpp
#include <iostream> 
using namespace std; 

int main() {
    // Declare a variable to store the year
    int year;
    
    // Prompt the user to input a year
    cout << "Enter a year: ";
    cin >> year;

    // Check for leap year conditions
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        // If conditions are met, it is a leap year
        cout << year << " is a leap year." << endl;
    } else {
        // If conditions are not met, it is not a leap year
        cout << year << " is not a leap year." << endl;
    }

    // Ending the program
    return 0;
}

Testing the Program with Different Input Values

  • Input: 2000
  • Output: 2000 is a leap year.
  • Input: 1900
  • Output: 1900 is not a leap year.
  • Input: 2024
  • Output: 2024 is a leap year.
tools

Programming

Related Articles