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
using System; class Program { static void Main() { Console.Write("Enter a year: "); int year = int.Parse(Console.ReadLine()); if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { Console.WriteLine($"{year} is a leap year."); } else { Console.WriteLine($"{year} is not a leap year."); } } }
Dry Run
Let's trace the year 1900 through the code
Input year
year = 1900
Check divisibility by 400
1900 % 400 = 300 (not zero), so false
Check divisibility by 4 and not by 100
1900 % 4 = 0 (true) and 1900 % 100 = 0 (true), so condition false because year % 100 == 0
Determine result
Not a leap year
| Check | Result |
|---|---|
| 1900 % 400 == 0 | False |
| 1900 % 4 == 0 | True |
| 1900 % 100 != 0 | False |
| Final leap year? | No |
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
using System; class Program { static void Main() { Console.Write("Enter a year: "); int year = int.Parse(Console.ReadLine()); if (DateTime.IsLeapYear(year)) { Console.WriteLine($"{year} is a leap year."); } else { Console.WriteLine($"{year} is not a leap year."); } } }
using System; class Program { static void Main() { Console.Write("Enter a year: "); int year = int.Parse(Console.ReadLine()); if (year % 400 == 0) { Console.WriteLine($"{year} is a leap year."); } else { if (year % 100 == 0) { Console.WriteLine($"{year} is not a leap year."); } else if (year % 4 == 0) { Console.WriteLine($"{year} is a leap year."); } else { Console.WriteLine($"{year} is not a leap year."); } } } }
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 O(1).
Which Approach is Fastest?
All approaches run in constant time, but using DateTime.IsLeapYear is simplest and less error-prone.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual condition check | O(1) | O(1) | Learning logic and control flow |
| DateTime.IsLeapYear method | O(1) | O(1) | Clean, reliable production code |
| Nested if statements | O(1) | O(1) | Clear step-by-step logic |
DateTime.IsLeapYear(year) method for cleaner code.year % 100 != 0 condition, causing incorrect leap year results.