Hey guys, I'm just going over some practice problems for my introductory C++ class and I'm struggling with finding a solution to converting this switch code to an if/else statement. I don't have the book yet(broke), so it's really hard trying to find a solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int x, y, z;
cout << “Enter 3 values: “;
cin >> x >> y >> z;
switch (y) {
case 2: switch (x) {
case 4: cout << y << endl;
break;
case 5: cout << z << endl;
}
break;
case 3: switch (z) {
case 2: cout << x + y << endl;
break;
}
break;
default: cout << “I’m Done” << endl;
}
Never knew you could use If/Switch. The instruction say if/else.
I'm struggling to understand the purpose and function of this code as well.
The user inputs 3 numbers, which are assigned to x,y,z in that order.
Then the program is aying if y meets whatever condition(I don't know what it is), then it does what?
Output that same number?
Never knew you could use If/Switch. The instruction say if/else.
No, that's not quite what was meant.
An if statement looks like this:
1 2 3 4
if (condition)
statement1;
else
statement2;
Now statement1 and statement2 can be as simple or as complex as you like. If necessary, it could be a block of several lines of code enclosed in braces { }.
It just happens that
1 2 3 4
switch (variable)
{
// case statements etc.
}
is a block of code which is regarded as a single statement, thus that entire structure can be dropped into place instead of statement1 or statement2
switch(variable)
{
case 1:
variable = 2; //Code to run if variable == 1 ...
break; //break ends the switch statement immediately
//if you don't break the switch continues testing all other cases,
//if we didn't break now, case 2: would have immediately run.
case 2:
//Code you want to run if variable == 2
break;
default:
//Code to run if no other cases tested as true
break;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
if(variable == 1)
{
//code you want to run if variable == 1
}
elseif(newVariable == 2)
{
//this code will run if newVariable is equal to 2
//also this code only runs if the argument in the previous if() tested as false.
}
elseif(variable == 3)
{
//all previous arguments tested as false, but this is true.
}
else //no parenthesis
{
//this runs if all other if's and else if's were false (much like the default: in a switch)
}
So pretty much the idea is that else if()'s are easier to use in shorter tests, or if you need to test multiple variables (also look into using AND(&&) OR(||) ). Switch/case is used when there are a lot of possible answers for a single variable.