A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400
Point You can use the following Boolean expressions to check whether a year is a leap year:
// A leap year is divisible by 4
bool isLeapYear = (year % 4 == 0);
// A leap year is divisible by 4 but not by 100
isLeapYear = isLeapYear && (year % 100 != 0);
// A leap year is divisible by 4 but not by 100 or divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
or you can combine all these expressions into one:
isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
Listing 3.6 gives a program that lets the user enter a year and checks whether it is a leap year.
Listing 3.6 LeapYear.cpp
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 cout << “Enter a year: “;
7 int year;
8 cin >> year;
9
10 // Check if the year is a leap year
11 bool isLeapYear =
12 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
13
14 // Display the result
15 if (isLeapYear)
16 cout << year << ” is a leap year” << endl;
17 else
18 cout << year << ” is a not leap year” << endl;
19
20 return 0;
21 }
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.