C If...Else and Switch
if, else if and else choose between paths. switch picks a branch by value; use break to stop at the end of a case.
ExampleC
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 70) {
printf("B\n");
} else {
printf("C\n");
}
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 3: printf("Wednesday\n"); break;
default: printf("Other\n");
}
printf("%s\n", (score >= 50) ? "pass" : "fail");
return 0;
}Output
B Wednesday pass
Quick check
What happens if you forget break in a switch case?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.