All lessonsOpen Open Open Open Open
3. Decisions
switch statements
0 of 5 activities0%
Reading 1
One value, many cases
switch compares an integer (or char) expression to a list of case labels. Each case usually ends with break so execution does not fall into the next case.
default runs when no case matches. It is optional but useful.
switch is a clean alternative to a long else if chain when you match exact values, not ranges.
switch (day) {
case 1:
cout << "Mon" << endl;
break;
case 2:
cout << "Tue" << endl;
break;
default:
cout << "other" << endl;
}Check 2
Why break
What does break do inside a switch case?
Fill in 3
Fallback label
Try it 4
Day name
Input is 2. Try 1 and 9.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Op labels
Read an integer op. If op is 1 print add, if 2 print sub, if 3 print mul, otherwise print unknown. Exact words.
main.cpp
Loading editor…