C/C++ Arena

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 task

Read a year and print leap or common.

Challenge 2

Read a month number (1 to 12) and print how many days it has in a year that is not a leap year. February has 28, April, June, September and November have 30, and the rest have 31. Any other number prints invalid.

Challenge 3

Now read a month and a year and print the number of days, so February has 29 days in leap years. Invalid months still print invalid. Input 2 2024 prints 29.

Previous: The ternary operator