C: Days in a month

Work out how many days a month has.

What to build

A switch in which several cases share one result.

Requirements

  • Read a month and a year.
  • Print the number of days in that month.
  • Print invalid if the month is not from 1 to 12.
  • A year is a leap year if it divides by 4 and not by 100, or if it divides by 400.

Input

One line with two whole numbers.

Output

One line.

Constraints

The year is from 1 to 9999.

Example

Input:

2 2024

Output:

29

Why it works

Months 4, 6, 9 and 11 all share one answer, so their cases can fall through to the same printf. This is one of the rare good uses of leaving out break.

Examples

Example 1 · Input
2 2024
Expected output
29
Example 2 · Input
2 2023
Expected output
28

Hints

Hint 1

Several cases can share one block by falling through.

Hint 2

February needs the leap year rule.

Hint 3

Use default for an invalid month.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int month, year;
    scanf("%d %d", &month, &year);
    switch (month) {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12:
        printf("31\n");
        break;
    case 4: case 6: case 9: case 11:
        printf("30\n");
        break;
    case 2:
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            printf("29\n");
        } else {
            printf("28\n");
        }
        break;
    default:
        printf("invalid\n");
    }
    return 0;
}

Lesson: Decisions: if, else and switch →