Cpp - Write program to check if the year is a leap year

Requirements

Write program to check if the year is a leap year

Create isLeapYear() function which uses several if and else statements to carry out these rules.

The function returns the bool value true if a year is a leap year and false otherwise.

The function takes an integer argument, the year to check.

Hint

Leap years, which have 366 days rather than 365, follow three rules:

  • If the year is divisible by 4, it is a leap year,
  • Unless the year is also divisible by 100, in which case it is not a leap year,
  • Unless the year is divisible by 400, and it's a leap year after all.

Demo

#include <iostream> 
 
bool isLeapYear(int year); 
 
int main() /*from  w  w  w  . ja v  a2s. c o m*/
{ 
    int input; 
    std::cout << "Enter a year: "; 
    std::cin >> input; 
    if (isLeapYear(input)) 
           std::cout << input << " is a leap year\n"; 
    else 
           std::cout << input << " is not a leap year\n"; 
    return 0; 
} 
 
bool isLeapYear(int year) 
{ 
    if (year % 4 == 0) 
    { 
           if (year % 100 == 0) 
           { 
                if (year % 400 == 0) 
                     return true; 
                else 
                     return false; 
           } 
           else 
                return true; 
    } 
    else 
           return false; 
}

Result

Related Exercise