Days in a month
Pick one of many cases with a switch statement. An easy embedded C problem (Decisions and loops), run and graded in the browser.
easy · Decisions and loops · switch
Return the number of days in month month, where 1 is January and 12 is December. Ignore leap years, so February has 28 days. Return 0 for any number that is not a month.
A switch statement is a tidy way to choose between many fixed values.
Starter code
int days_in_month(int month) {
switch (month) {
case 2:
return 28;
default:
return 0;
}
}Example tests
January
printf("%d\n", days_in_month(1));Expected output:
31February
printf("%d\n", days_in_month(2));Expected output:
28Learn it first
- Decisions and loops · Choosing with if and switch, repeating with while and for, and the loop that never ends.
More Decisions and loops problems
- The larger of two · Choose between two values with an if statement.
- Sign of a number · Handle three cases with if, else if and else.
- Keep a value in range · Limit a value to a minimum and a maximum.
- Sum the numbers up to n · Repeat an addition with a loop.
- Count the digits · Loop until a value runs out.
- Raise to a power · Multiply repeatedly inside a loop.
- Countdown · Print inside a loop that counts down.
- Fix: the heater never turns on · A comparison that is really an assignment.
- Fix: the countdown never ends · A loop counting down to zero with an unsigned counter can never stop.
- Fix: the maximum is always the last reading · A semicolon after an if condition turns the update into a statement that always runs.
- Greenhouse: switch the pump with a band · Decide whether the pump runs, with a band so the relay does not chatter.