Check for Leap Year
This exercise teaches you how to create a function in C++ to determine whether a given year is a leap year or not. Leap years help synchronize the calendar year with the solar year, occurring roughly every four years.
However, the actual rule includes specific exceptions: a year is a leap year if it is divisible by 4, but not by 100 unless it is also divisible by 400. You will implement this logic using a modular approach.
Implementation Details
1. Boolean Logic
Using bool as a return type is the most efficient way to represent "Yes/No" or "True/False" conditions.
2. Modulo Operator
The % operator is essential here to check divisibility (e.g., year % 4 == 0).
3. Logical Operators
Combining conditions with && (AND) and || (OR) allows for a concise, one-line rule.
Logic Tip:
Remember the 400-year rule! The year 2000 was a leap year, but 1900 was not, despite both being divisible by 4 and 100.
Objective
- 1. Define a function
isLeapYear(int year). - 2. Implement the nested logic:
(divisible by 4 AND NOT 100) OR (divisible by 400). - 3. Return a
boolvalue based on the result. - 4. Use an
ifstatement inmain()to print a user-friendly message.
Example C++ Exercise
#include <iostream>
using namespace std;
// Function to determine if a year is a leap year
bool isLeapYear(int year) {
// Logic: (divisible by 4 AND not 100) OR (divisible by 400)
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
// Call the function to check if it is a leap year
if (isLeapYear(year)) {
cout << year << " is a leap year." << endl;
} else {
cout << year << " is not a leap year." << endl;
}
return 0;
}
Example Output:
2024 is a leap year.