C bootcamp · Lab 30

Day of the week

easySwitch10 minLesson: Switch

Read the question, write C on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read an integer 1–7 and print the weekday: 1 Monday, 2 Tuesday, …, 7 Sunday.

Any other number prints Invalid. Use a switch, not a chain of ifs.

Input. One integer.

Output. Monday … Sunday, or Invalid.

Examples

Example 1
Input
1
Output
Monday
Example 2
Input
7
Output
Sunday
Example 3
Input
0
Output
Invalid
Hint
  1. switch (d) { case 1: printf("Monday\n"); break; … default: printf("Invalid\n"); }
  2. Do not forget break, or cases fall through.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <stdio.h>

int main(void) {
  int d;
  if (scanf("%d", &d) != 1) return 1;
  switch (d) {
    case 1: printf("Monday\n"); break;
    case 2: printf("Tuesday\n"); break;
    case 3: printf("Wednesday\n"); break;
    case 4: printf("Thursday\n"); break;
    case 5: printf("Friday\n"); break;
    case 6: printf("Saturday\n"); break;
    case 7: printf("Sunday\n"); break;
    default: printf("Invalid\n"); break;
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.