Summary - Conditionals
- C course
- Beginner
- Lesson 41/116
- 5 min
Combine if, switch and ternary to write a day-of-week app.
Summary - Conditionals
In this section you learned if, else if, else, switch, case, break, default and the ternary. Now we'll combine them in a day-of-week app.
The app takes a number (1-7) and prints the weekday. We'll do it first with if/else, then with switch; you'll see how both methods work.
Practice Write the day with if/else
Write a C program. Declare int day = 3;. With if (day == 1) print printf("Monday\n");, with else if (day == 2) print printf("Tuesday\n");, with else if (day == 3) print printf("Wednesday\n");, with else print printf("Other\n");. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare day, print the day with if/else if/else
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int day = 3;
if (day == 1) {
printf("Monday\n");
} else if (day == 2) {
printf("Tuesday\n");
} else if (day == 3) {
printf("Wednesday\n");
} else {
printf("Other\n");
}
return 0;
}Expected output
Wednesday
Practice Write the day with switch
Write a C program. Declare int day = 3;. With switch (day) print case 1: printf("Monday\n"); break;, case 2: printf("Tuesday\n"); break;, case 3: printf("Wednesday\n"); break;, default: printf("Other\n");. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare day, print the day with switch
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other\n");
}
return 0;
}Expected output
Wednesday
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which value type does switch work with?
switch (x) { case 1: ...; }- Only strings
- Integer or char Correct answer
- Floating-point
- Arrays
Explanation: switch works only with integers or chars.
2 Even/odd with ternary
printf("%s
", (n % 2 == 0) ? "Even" : ____);
printf("%s
", (n % 2 == 0) ? "Even" : "Odd");
Explanation: When false the string "Odd" is returned.
3 Match the condition statements
| Term | Meaning |
|---|---|
if |
Single condition |
else if |
Chained condition |
switch |
Multi-way |
? : |
One line |