The switch statement allows you to select one of many code blocks to execute, based on the value of a variable or expression. Itβs a cleaner alternative to multiple if-else statements when checking a variable against several constant values.
switch (expression) {
case constant1:
// code to execute if expression == constant1
break;
case constant2:
// code to execute if expression == constant2
break;
...
default:
// code to execute if no case matches
}
expression is evaluated once.case constant.break exits the switch; without it, execution falls through to the next case.default runs if no cases match (optional but recommended).
#include <iostream>
using namespace std;
int main() {
int day;
cout << "Enter day number (1 to 7): ";
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day number" << endl;
}
return 0;
}
- The program reads a number from 1 to 7.
- The switch matches this number to the corresponding day name.
- break statements prevent "fall through" β without them, all subsequent cases would run.
- If the number is not between 1 and 7, the default case prints an error message.
switch for clear, readable multiple-choice decision making.case checks one possible value.break prevents executing unwanted cases.default handles unexpected values.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!