C Program to Check Leap Year with Output and Explanation
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) to decide if a year is leap and prints the result accordingly.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } return 0; }
Dry Run
Let's trace the input year 2024 through the code
Input year
year = 2024
Check divisibility by 400
2024 % 400 = 24 (not zero), so false
Check divisibility by 4 and not by 100
2024 % 4 = 0 (true) and 2024 % 100 = 24 (not zero), so true
Decide leap year
Condition is true, so 2024 is leap year
Print result
Output: '2024 is a leap year.'
| Step | Condition | Result |
|---|---|---|
| Check year % 400 == 0 | 2024 % 400 == 0 | False |
| Check year % 4 == 0 | 2024 % 4 == 0 | True |
| Check year % 100 != 0 | 2024 % 100 != 0 | True |
| Final leap year condition | (False) || (True && True) | True |
Why This Works
Step 1: Divisible by 400 means leap year
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 by 100 means leap year
If the year is divisible by 4 but not by 100, it is a leap year, so we check year % 4 == 0 && year % 100 != 0.
Step 3: Otherwise, not a leap year
If neither condition is true, the year is not a leap year.
Alternative Approaches
#include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); if (year % 400 == 0) { printf("%d is a leap year.\n", year); } else if (year % 100 == 0) { printf("%d is not a leap year.\n", year); } else if (year % 4 == 0) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } return 0; }
#include <stdio.h> int isLeapYear(int year) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } int main() { int year; printf("Enter a year: "); scanf("%d", &year); if (isLeapYear(year)) { printf("%d is a leap year.\n", year); } else { printf("%d is not a leap year.\n", year); } 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
The program uses a fixed amount of memory for variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using a function improves readability but does not affect speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Single if condition | O(1) | O(1) | Simple and concise code |
| Nested if-else | O(1) | O(1) | Clear stepwise logic |
| Function-based check | O(1) | O(1) | Code reuse and clarity |