Step 6 of 6
Challenge: leap years
This challenge is about translating an English rule into a precise condition, which is a big part of programming.
The leap year rule, as a sentence: a year is a leap year if it's divisible by 4, except years divisible by 100, which are not leap years, unless they're also divisible by 400.
Break it down
"Divisible by N" means the remainder is zero: year % N == 0. Then work through the cases:
| Year | div by 4 | div by 100 | div by 400 | Leap? |
|---|---|---|---|---|
| 2023 | no | no | no | no |
| 2024 | yes | no | no | yes |
| 1900 | yes | yes | no | no |
| 2000 | yes | yes | yes | yes |
A table like this is a great tool: it lists the tricky cases, and you can use it to test your condition afterwards. The same approach works for any rule.
Two ways to write it
You can write one combined condition with &&, || and parentheses, or a chain of if/else if that checks the most specific rule first. Here's the chain style on a different rule (a number is "fizz" if divisible by 3, "buzz" if by 5, "fizzbuzz" if both):
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
if (n % 15 == 0) {
printf("fizzbuzz\n");
} else if (n % 3 == 0) {
printf("fizz\n");
} else if (n % 5 == 0) {
printf("buzz\n");
} else {
printf("%d\n", n);
}
return 0;
}
30
fizzbuzz
The most specific case (divisible by both) had to come first, or 30 would stop at "fizz".
Your turn: read a year and print leap or common.