C++ Code Example: check leap year in if else statement

A normal year has 365 days. Every four years, however, there is a leap year with 366 days. This is because the earth does not need exactly 365 days to travel once around the sun, but about a quarter day more. So a year has one day more every 4 years.

So that the calculation is correct, there is no leap year every 100 years. Nevertheless, every four hundred years a leap year takes place. This concerns the years 2000, 2400 etc.

Code Example

The isLeapYear function takes an integer year as input and returns a boolean value, indicating whether or not the input year is a leap year.

The function checks for three conditions:

  • If the year is not divisible by 4, it is not a leap year.
  • If the year is divisible by 400, it is a leap year.
  • If the year is divisible by 100, but not by 400, it is not a leap year.
  • Otherwise, it is a leap year.

The main function calls the isLeapYear function with a value of 2020, and prints the appropriate message indicating whether or not the year is a leap year.

#include <iostream>
using namespace std;

bool isLeapYear(int year) {
    if (year % 4 != 0) {
        return false;
    } else if (year % 400 == 0) {
        return true;
    } else if (year % 100 == 0) {
        return false;
    } else {
        return true;
    }
}

int main() {
    int year = 2020;

    if(isLeapYear(year)) {
        cout << year << " is a leap year" << endl;
    } else {
        cout << year << " is not a leap year" << endl;
    }

    return 0;
}
Output
2020 is a leap year