The switch statement is c++ multi-way branch statement. It is used to take the place of long if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined.
This is a simple C++ program that demonstrates the use of a switch statement. The program prompts the user to enter a value for the variable num. It then uses a switch statement to check the value of num and print a message based on the value.
If num is 1, 2, or 3, the program will print a message indicating the value of num and the corresponding case. If num is any other value, the program will print a default message indicating the value of num.
Here's an example of how the program might run:
Enter the Case to Present :2
Case2: Value is: 2
In this example, the user entered the value 2, so the program printed the message "Case2: Value is: 2".
Note that the break statement is used after each case to exit the switch statement and prevent the program from executing the code in the subsequent cases. This is an important part of how switch statements work in C++.
#include <iostream> using namespace std; int main() { int num; cout<<"\nEnter the Case to Present :"; cin>>num; switch(num) { case 1: cout<<"\nCase1: Value is: "<<num<<endl; break; case 2: cout<<"\nCase2: Value is: "<<num<<endl; break; case 3: cout<<"\nCase3: Value is: "<<num<<endl; break; default: cout<<"\nDefault: Value is: "<<num<<endl; break; } return 0; }To download raw file Click Here
Enter the Case to Present :4 Default: Value is: 4
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions