+ 1
can anyone write a simple program based on switch statement for my better understanding?
3 Answers
+ 3
int x = 2;
switch(x) {
case 1:
cout << "One";
break;
case 2:
cout << "Two";
break;
case 3:
cout << "Three";
break;
default:
cout << "Other";
}
//prints "Two"
This code is equivalent to:
int x = 2;
if (x == 1) {
cout << "One";
} else if (x == 2) {
cout << "Two";
} else if (x == 3) {
cout << "Three";
} else {
cout << "Other";
}
Of course, you can use other data types as well, not just int.
String country = "Italia";
switch(country) {
case "Russia":
etc.
+ 2
The best example is the calculator, try to think how to make the 4 operations as a switch choices and write the code by your self it's much better for your understanding
+ 1
#include<iostream.h>
main()
{
int n;
switch(n)
{
cout<<"enter n";
cin>>n;
case 1: cout<<"hai";
case 2: cout<<"hello";
default: cout<<"choose correct choice";
}
}