Switch Statement in C++
In C++, the switch statement is used when multiple situations need to be evaluated primarily based on the value of a variable or an expression. switch statement acts as an alternative to multiple if statements or if-else ladder and has a cleaner structure and it is easy for handling multiple conditions.
Syntax of C++ switch
switch (expression) {
case value1:
// code to be executed if the value of expression is value1.
break;
case value2:
// code to be executed if the value of expression is value2.
break;
//…..
default:
// code to be executed if expression doesn't match any case.
}
Flowchart of switch in C++
Example pf switch in C++
The below example demonstrates the use of switches in decision-making. In the below program, we are given a character and you have to give output as per the given condition: if the given input is A then print GFG, and if the given input is B print w3wiki else print invalid input.
C++
// C++ program to use switch case and print certain output // based on some conditions #include <iostream> using namespace std; int main() { char input = 'B' ; switch (input) { // if the input character is A then print GFG case 'A' : cout << "GFG" << endl; break ; // if the input character is B then print w3wiki case 'B' : cout << "w3wiki" << endl; break ; default : // if th einput character is invalid then print // invalid input cout << "invalid input" << endl; } return 0; } |
w3wiki
Decision Making in C++
Decision-making in C++ involves the usage of conditional statements (also called decision control statements) to execute specific blocks of code primarily based on given situations and their results.
So basically, in decision-making, we evaluate the conditions and make a decision about which part of the code should be executed or not. It allows selective code execution which is crucial for controlling the flow of a program and making it more dynamic.