A year consisting of 366 days instead of the usual 365 days is a leap year. Every fourth year is a leap year in the Gregorian calendar system. In this article, we will learn how to write a C++ program to check leap year.
A year is a leap year if one of the following conditions is satisfied:
- The year is a multiple of 400.
- The year is a multiple of 4 but not a multiple of 100.
Algorithm to Check Leap Year
The algorithm implements the conditions specified above to check for leap year.
if (year % 400 = 0) return true (Leap year) else if (year % 100 = 0) return false (Not a leap year) else if (year % 4 = 0) return true (Leap year) else return false (Not a leap year) endif
Leap Year Program in C++
C++
// C++ program to check if a given // year is a leap year or not #include <iostream> using namespace std;
// Function to check leap year bool checkYear( int year)
{ if (year % 400 == 0) {
return true ;
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
return false ;
}
// leap year if not divisible by 100
// but divisible by 4
else if (year % 4 == 0) {
return true ;
}
// all other years are not leap years
else {
return false ;
}
} // Driver code int main()
{ int year = 2000;
checkYear(year) ? cout << "Leap Year"
: cout << "Not a Leap Year" ;
return 0;
} |
Output
Leap Year
Complexity Analysis
- Time Complexity: Since there are only if statements in the program, its time complexity is O(1).
- Auxiliary Space: O(1)
Article Tags :
Recommended Articles