Here, we have used nested
if statements to check whether the year given by the user is a leap year or not.
First, we check
if year is divisible by
4 or not. If it is not divisible, then it is not a leap year.
If it is divisible by 4, then we use an inner if statement to check whether year is divisible by
100.
If it is not divisible by
100, it is still divisible by
4 and so it is a
leap year.
We know that the century years are not leap years unless they are divisible by
400.
So, if
year is divisible by
100, another inner
if statement checks whether it is divisible by
400 or not.
If it's divisible by
400, it is a leap year. Otherwise, it's not a leap year.
Check Leap Year Using Logical Operators :
We can combine the conditions required for a leap year into a single
if...else statement using the
&& and
|| operators.
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
// if year is divisible by 4 AND not divisible by 100
// OR if year is divisible by 400
// then it is a leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
cout << year << " is a leap year.";
}
else {
cout << year << " is not a leap year.";
}
return 0;
}
Output :
Enter a year: 2024
2024 is a leap year.