Leap Year Checker in C++
This document provides a C++ program that checks whether a given year is a leap year. It includes a detailed explanation of the program structure and comments for clarity.
Program Code
#include <iostream>
using namespace std;
/**
* @brief Checks if a given year is a leap year.
* @param year The year to be checked.
* @return True if the year is a leap year, false otherwise.
*/
bool isLeapYear(int year) {
// Leap year is divisible by 4
if (year % 4 == 0) {
// If the year is a century year, it must be divisible by 400
if (year % 100 == 0) {
// Century year divisible by 400 is a leap year
if (year % 400 == 0) {
return true;
} else {
return false;
}
} else {
// Non-century year divisible by 4 is a leap year
return true;
}
} else {
// Year not divisible by 4 is not a leap year
return false;
}
}
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
if (isLeapYear(year)) {
cout << year << " is a leap year." << endl;
} else {
cout << year << " is not a leap year." << endl;
}
return 0;
}
Program Explanation
The program is structured as follows:
- Include Directives:The program includes the
<iostream>
header file, which is required for input and output operations. - Using Namespace:The
using namespace std;
directive is used to avoid prefixing standard library names withstd::
. - Function Definition (
isLeapYear
):TheisLeapYear
function takes an integer year as a parameter and returns a boolean value indicating whether the year is a leap year.- First, the function checks if the year is divisible by 4.
- If the year is divisible by 4, it checks if it is a century year (divisible by 100).
- If it is a century year, it further checks if it is divisible by 400.
- The year is considered a leap year if it meets the conditions outlined above; otherwise, it is not.
- Main Function:The
main
function is the entry point of the program.- It prompts the user to enter a year.
- The
isLeapYear
function is called with the entered year, and the result is used to display whether the year is a leap year or not.
Documentation
The program is documented with comments to explain the purpose of each part of the code:
- Comments are added to the
isLeapYear
function to describe the logic behind checking leap years. - Inline comments in the
main
function explain user interactions and the flow of the program.