Leap year checker
A leap year adds an extra day to our calendar to keep it in line with Earth's orbit around the Sun. A leap year occurs once every 4 years. However, this frequency doesn't align us accurately. Because of this, not every 4 years is a leap year. The general rule is that if the year is divisible by 100 and not divisible by 400, the leap year is skipped
Using if and else statements, together with the AND operator and make a program that prompts the user to enter a year and lets them know if that is a leap year or not.
Hint
To check if a year is a leap year it has to be divisible by 4 AND the year has to not be a skip year (as defined by it being divisible by 100, but not 400)
Answer
#include <iostream>
int main()
{
std::cout << "What year do you want to check?";
int year;
std::cin >> year;
// If the year is divisible by 4 AND the year is not a skipp year (as defined by it being divisible by 100, but not 400)
bool is_leapyear = (year%4==0) && !(year%100==0 && year%400!=0);
if (is_leapyear)
{
std::cout << year << " is a leap year!";
}
if (!is_leapyear)
{
std::cout << year << " is not a leap year!";
}
}
Here the logic is put inside a variable (
is_leapyear) to label the logic, add context to the code, and save the computer from doing the same calculation twice.