Go Program to Check Leap Year with Output and Explanation
if (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) to decide if the year is leap or not.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func main() { year := 2024 if (year%400 == 0) || (year%4 == 0 && year%100 != 0) { fmt.Printf("%d is a leap year\n", year) } else { fmt.Printf("%d is not a leap year\n", year) } }
Dry Run
Let's trace the year 2024 through the code
Set year
year = 2024
Check divisibility by 400
2024 % 400 = 24 (not zero)
Check divisibility by 4 and not by 100
2024 % 4 = 0 and 2024 % 100 = 24 (not zero), condition true
Print result
"2024 is a leap year"
| Check | Result |
|---|---|
| 2024 % 400 == 0 | false |
| 2024 % 4 == 0 | true |
| 2024 % 100 != 0 | true |
| Leap year? | true |
Why This Works
Step 1: Divisible by 400 means leap year
If year % 400 == 0, the year is a leap year because every 400 years we add a leap day.
Step 2: Divisible by 4 but not 100 means leap year
If the year is divisible by 4 but not by 100, it is a leap year to correct the calendar.
Step 3: Otherwise not leap year
If neither condition is true, the year is not leap because it doesn't fit leap year rules.
Alternative Approaches
package main import "fmt" func isLeapYear(year int) bool { return (year%400 == 0) || (year%4 == 0 && year%100 != 0) } func main() { year := 1900 if isLeapYear(year) { fmt.Printf("%d is a leap year\n", year) } else { fmt.Printf("%d is not a leap year\n", year) } }
package main import "fmt" func main() { year := 2000 switch { case year%400 == 0: fmt.Printf("%d is a leap year\n", year) case year%4 == 0 && year%100 != 0: fmt.Printf("%d is a leap year\n", year) default: fmt.Printf("%d is not a leap year\n", 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, so the space complexity is constant O(1).
Which Approach is Fastest?
All approaches use simple arithmetic checks and run in constant time; using a function or switch is mostly for code clarity, not speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Inline if-else | O(1) | O(1) | Simple quick checks |
| Function encapsulation | O(1) | O(1) | Code reuse and clarity |
| Switch statement | O(1) | O(1) | Readable multiple condition checks |