What is switch Statement in C++?
The switch statement is used to execute one block of code from multiple options based on the value of a variable.
It compares the value with different cases and runs the matching one.
Syntax of switch Statement
switch (expression) {
case value1:
// code to execute
break;
case value2:
// code to execute
break;
default:
// code if no match is found
}
Explanation:
- The expression is evaluated once.
- Its value is compared with each case value.
- If a match is found, that case block executes.
- break is used to stop execution after a case.
- default runs when no case matches.
Algo of Switch Statement
- First, the value of the expression is checked.
- Then it is compared with each case.
- When a match is found, that case runs.
- break stops the program from checking further cases.
- If no case matches, default executes.
Example
#include <iostream>
using namespace std;
int main() {
int day = 2;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
default:
cout << "Invalid Day";
}
return 0;
}
Output:
Tuesday
Explanation:
- The value of day is 2.
- It matches with case 2.
- So, "Tuesday" is printed.
- break stops further execution.
Summary:
- switch statement is used to select one option from many.
- It works with fixed values instead of conditions.
- break prevents unwanted execution.
- Without break, multiple cases can execute.
- default handles unmatched cases.