In this example, I’ll show you How to check Leap Year or Not in C++.
Check Leap Year or Not in C++
To check whether the input year is a leap year or not a leap year in C++ Programming, you have to ask to the user to enter the year and start checking for the leap year. To check that the year is a leap year or not, following these rules:
- If year is divided by 4 but not by 100, then it is a leap year.
- If year is divided by both 100 and 400, then it is a leap year.
- If year is divided by 400, then it is a leap year.
- And in all other cases, it is not a leap year.
All years which are perfectly divisible by 4 are leap years except for century years (years ending with 00) which is leap year only it is perfectly divisible by 400.
For example: 2012, 2004, 1968 etc are leap year but, 1971, 2006 etc are not leap year. Similarly, 1200, 1600, 2000, 2400 are leap years but, 1700, 1800, 1900 etc are not.
C++ Programming Code to Check Leap Year or Not
Following C++ program ask to the user to enter the year to check whether it is a leap year or not, then display it on the screen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; if (year % 4 == 0) { if (year % 100 == 0) { if (year % 400 == 0) cout << year << " is a leap year."; else cout << year << " is not a leap year."; } else cout << year << " is a leap year."; } else cout << year << " is not a leap year."; return 0; } |
When the above C++ program is compile and executed, it will produce the following result. Above C++ Programming Example Output (for leap year):