C++ Switch case statements
A control flow statement known as a switch in C++ enables a program to carry out various operations depending on the value of an expression. It offers a clearer approach to writing several if-else expressions.
Basic syntax of switch-case statement:
switch (expression) {
case value1:
// code to execute when expression equals value1
break;
case value2:
// code to execute when expression equals value2
break;
...
default:
// code to execute when expression doesn't match any case
break;
}
In this instance, the “expression” is assessed, and its value is contrasted with those of each “case.” A code block is performed if the value matches any of the “case” values. If the “case” value does not match the expression value, the “default” case code block is run. (if present).
Here’s an example of the switch-case statement:
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday";
break;
case 2:
std::cout << "Tuesday";
break;
case 3:
std::cout << "Wednesday";
break;
case 4:
std::cout << "Thursday";
break;
case 5:
std::cout << "Friday";
break;
default:
std::cout << "Weekend";
break;
}
return 0;
}
Output:
Wednesday
In this illustration, the variable “day” is used to hold a weekday that is represented as an integer number. Based on the integer number, we utilise the switch statement to output the name of the day. We have a default case for all other values and cases for values 1 through 5, which correspond to Monday through Friday. (representing the weekend).
As a result, since “day” has the value 3 in this situation, the code block related to case 3 is performed, producing the string “Wednesday”.
In general, the C++ switch statement offers a condensed method of constructing numerous if-else statements. When there are too many cases or sophisticated expressions are involved, it should be utilised cautiously and avoided.
#include <iostream>
int main() {
char grade;
std::cout << "Enter your grade (A/B/C/D/F): ";
std::cin >> grade;
switch(grade) {
case 'A':
std::cout << "Excellent!\n";
break;
case 'B':
std::cout << "Good job!\n";
break;
case 'C':
std::cout << "Not bad!\n";
break;
case 'D':
std::cout << "Could be better.\n";
break;
case 'F':
std::cout << "You failed.\n";
break;
default:
std::cout << "Invalid input.\n";
}
return 0;
}
Output:
If you input 'A' as the grade, the output will be "Excellent!".
If you input 'B' as the grade, the output will be "Good job!".
If you input 'C' as the grade, the output will be "Not bad!".
If you input 'D' as the grade, the output will be "Could be better.".
If you input 'F' as the grade, the output will be "You failed.".
If you input any other character, the output will be "Invalid input."