Check if a year is a leap year

Description: Write is_leap(int year). Test 1900, 2000, 2024 and 2026.

Hint:

  • Use % and the three rules.

Solution

#include <iostream>

bool is_leap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}

int main() {
    std::cout << std::boolalpha;
    for (int y : {1900, 2000, 2024, 2026}) {
        std::cout << y << " -> " << is_leap(y) << '\n';
    }
}
Output

1900 -> false
2000 -> true
2024 -> true
2026 -> false

How it works

  • 1900 is divisible by 100 but not by 400, so it is not a leap year. 2000 is divisible by 400, so it is.

Read C++ Operators.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.