Just like the if-else statement, the switch-case statement is another tool for controlling the flow of a program.
However, unlike an if-else statement, a switch-case statement can evaluate multiple conditions at once. This can be particularly useful in scenarios where you’re dealing with a handful of possibilities and you want to do something different depending on that possibility. For example, let's imagine you are building a system to grade the A.I predictions for financial stock predictions. The stock prediction can be graded as 'A', 'B', 'C', 'D', 'F'.
We can use a switch-case statement like so:
1char grade = 'B';
2switch (grade) {
3 case 'A' :
4 cout << "Excellent!";
5 break;
6 case 'B' :
7 case 'C' :
8 cout << "Well done";
9 break;
10 case 'D' :
11 cout << "You passed";
12 break;
13 case 'F' :
14 cout << "Better try again";
15 break;
16 default :
17 cout << "Invalid grade";
18}
19cout << "\nYour grade is : " << grade;
In the above code, the switch statement evaluates the variable 'grade'. Each 'case' checks whether the 'grade' matches the character it is testing for. If it does, it runs the code inside the case statement and breaks out of the switch statement. The 'default' case runs if no other case matched.
In summary, while if-else statements are effective for simpler conditions, switch-case statements offer greater readability and structure for complex, multi-condition scenarios.
xxxxxxxxxx
using namespace std;
int main() {
char grade = 'B';
switch(grade) {
case 'A' :
cout << "Excellent!";
break;
case 'B' :
case 'C' :
cout << "Well done";
break;
case 'D' :
cout << "You passed";
break;
case 'F' :
cout << "Better try again";
break;
default :
cout << "Invalid grade";
}
cout << "\nYour grade is : " << grade;
return 0;
}