C++ Program to Check Leap Year with Output and Explanation
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) to print if the year is leap or not.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { cout << year << " is a leap year." << endl; } else { cout << year << " is not a leap year." << endl; } return 0; }
Dry Run
Let's trace the year 2024 through the code to see how it checks for leap year.
Input year
year = 2024
Check divisibility by 400
2024 % 400 = 24 (not zero), so condition false
Check divisibility by 4 and not by 100
2024 % 4 = 0 (true) and 2024 % 100 = 24 (not zero), so condition true
Print result
Print '2024 is a leap year.'
| Check | Condition Result |
|---|---|
| year % 400 == 0 | false |
| year % 4 == 0 && year % 100 != 0 | true |
Why This Works
Step 1: Divisible by 400
If a year divides evenly by 400, it is always a leap year, so we check year % 400 == 0 first.
Step 2: Divisible by 4 but not 100
If not divisible by 400, a year must be divisible by 4 but not by 100 to be leap, checked by year % 4 == 0 && year % 100 != 0.
Step 3: Otherwise not leap
If neither condition is true, the year is not a leap year.
Alternative Approaches
#include <iostream> using namespace std; int main() { int year; cout << "Enter a year: "; cin >> year; if (year % 400 == 0) { cout << year << " is a leap year." << endl; } else { if (year % 100 == 0) { cout << year << " is not a leap year." << endl; } else if (year % 4 == 0) { cout << year << " is a leap year." << endl; } else { cout << year << " is not a leap year." << endl; } } return 0; }
#include <iostream> using namespace std; bool isLeapYear(int year) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } 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; }
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic and logical operations regardless of input size, so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store the year and results, so space complexity is constant O(1).
Which Approach is Fastest?
All approaches run in constant time, but using a function improves code readability without affecting performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single if condition | O(1) | O(1) | Simple and concise code |
| Nested if-else | O(1) | O(1) | Clear step-by-step logic |
| Function-based check | O(1) | O(1) | Reusable and organized code |