int number;
cin>>number;
switch (number)
{
case 1:
cout<<"My Favourite Subject is";
break;
case 2:
cout<<"Fundamentals of Programming";
break;
case 3:
cout<<"Exit";
break;
default:
cout<<"Invalid Data";
}
views:
372answers:
8Check whether number
is equal to the first value from switch, if equal then output text, otherwise(else) check next number.
if ( number == /*put here value to check*/ )
// print some text
else
// do something else
You replace switch statement with if-else
if (number == 1)
{
}
else if (number == 2)
{
}
...
{
}
else
{
// default here
}
Replace the case statement with an if statement:
if (number == 1) {
cout<<"My Favourite Subject is";
} else if (number == 2) {
cout<<"Fundamentals of Programming";
} else if (number == 3) {
cout<<"Exit";
} else {
cout<<"Invalid Data";
}
if (number == 1) {
cout << "blah1";
}
else if (number == 2) {
cout << "blah2";
}
else if (number == 3) {
cout << "blah3";
}
else {
cout << "default";
}
This is my favorite, even though it is not what you asked for:
string res =
number==1 ? "My Favourite Subject is" :
number==2 ? "Fundamentals of Programming" :
number==3 ? "Exit" :
number==4 ? "Invalid Data" :
"";
cout<<res;
The good side here is that you don't have to constrain yourself to integer comparison. Instead of number==1 you can use any kind of complexComparisonReturningBoolean(number).
Try :
if (number < 1 || number > 3) {
This helps you get more math expertise than just checking for equality.
//
} else if (number == 1) {
//
} else if (number/2 == 1) {
//
} else if ((number - 1)/ 2 == 1) {
//
}
//Hey this is fun!
int number;
cin>>number;
// ultra const!
static const char const * const table[] =
{
"Invalid Data",
"My Favourite Subject is",
"Fundamentals of Programming",
"Exit"
};
cout<<table[number&3];
//Who needs if statements!!?
Also just for fun: Just use capital letters and semi-colon instead of colon. Ah, and don't forget to add an evil macro :)
#define SWITCH(s) for(int switch_=s, b=1;b;b=0) {
#define CASE(n) } if ( switch_ == n ) {
#define DEFAULT }
int number;
cin>>number;
SWITCH(number)
{
CASE(1);
cout << "My Favourite Subject is";
break;
CASE(2);
cout << "Fundamentals of Programming";
break;
CASE(3);
cout << "Exit";
break;
DEFAULT;
cout << "Invalid Data";
}
This kill the 'switch' and if 'for' loop are not allowed, it is also possible to use a BREAK macro, but it is even more evil.