Leap Year Check in C++

Leap year in C++: 2000 is, 1900 isn't. Divisible by 4 is not the whole rule.

BeginnerConditional ProgramsExample 4 of 4
leap-year-check.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int year;
6
7 cout << "Enter a year: ";
8 cin >> year;
9
10 if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
11 cout << year << " is a leap year" << endl;
12 } else {
13 cout << year << " is not a leap year" << endl;
14 }
15
16 return 0;
17}

Output

Enter a year: 2024
2024 is a leap year

What's going on

A leap year in C++ is not "divisible by 4". 1900 is divisible by 4 and is not a leap year. 2000 is. The Gregorian rule is: leap if divisible by 400, or divisible by 4 but not by 100.

#include <iostream>

cout and cin. Same as Hello World.

int year;

A calendar year. 2024 fits in int. Don't overthink the type.

cout << "Enter a year: ";

cin >> year;

The sample uses 2024. Letters fail the stream; then the if runs on whatever year still holds.

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

Read it as two ways to be a leap year:

1.Divisible by 4, and not a century (% 100 != 0). 2024 yes. 1900 no, because 1900 % 100 is 0.
2.Divisible by 400. 2000 yes. 1900 no (1900 % 400 is 300).

The parentheses matter. && binds tighter than ||, so this grouping matches the English rule. Drop the inner parens and you can still get lucky on some years and fail on 2000 depending how you rewrite it. Keep them.

Worked years:

2024 — % 4 == 0, % 100 != 0 → leap. That's the output on this page.
2023 — % 4 is 3 → not leap. If your program says it is, you never tested remainder.
1900 — % 4 == 0 and % 100 == 0, but % 400 != 0 → not leap. The usual homework bug is calling this a leap year.
2000 — century, but % 400 == 0 → leap.
2100 — same shape as 1900 → not leap.

Nested ifs are the same logic, just taller:

if (year % 400 == 0) leap

else if (year % 100 == 0) not leap

else if (year % 4 == 0) leap

else not leap

People like this order because 400 is checked first. The one-liner in the code is equivalent.

February 29 exists only in a leap year. This program does not build a date. It only answers the year question. If you later write a day-of-year function, this is the test that function has to call.

return 0;

Done. Wrong answers almost always mean the condition used only % 4.