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
- Start the program.
- Prompt the user to enter a year.
- Read the year from user input.
- Check if the year is divisible by 4 but not by 100, or if it is divisible by 400.
- If the conditions are met, display that the year is a leap year.
- If the conditions are not met, display that the year is not a leap year.
- 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.