# Homework help! changing from a switch statement to if-else

• 03-07-2013
Rachel Hyde
Homework help! changing from a switch statement to if-else
Hi! This is my homework problem (for reference)
Please change the switch statement in the following program into an if-else statement (else if or
nested if-else statement may be necessary).
Attachment 12577
Attachment 12578
and so far on my code i have gotten to here, but my book doesn't give any explanation on what the equivalent of break; default is in if-else so i don't really know what it means nor how to do that line. any suggestions?

Attachment 12576
Attachment 12579
• 03-07-2013
Tclausex
break is not needed for if-else because it's a branching decision. Either the if-consequent is executed, or the else-alternate is executed. With switch, the behavior is to fall through (which can be useful) so you put breaks to avoid executing the successive statements.
• 03-07-2013
Rachel Hyde
okay, so for my next line i would have } else if((number !=1)||(number!=-1)||(number !=0)); ?
• 03-07-2013
Tclausex
Well, let's see if I can explain it in the most universal sense

Code:

``` if( predicate )   consequent ;```
Here we execute the consequent, only conditionally. That is, only if the predicate is true. Otherwise, we move on to whatever code follows.
Code:

```  if( predicate )     consequent ;   else     alternate ;```
In the above code, the predicate is tested for its boolean evaluation - true or false. If its true, the consequent is executed and the alternate is bypassed. If it is false, the consequent is bypassed and the alternate is executed. So, what part of this construct to you think is equivalent to 'default'?

Code:

```  if( predicate-1 )     consequent-1 ;   else if( predicate-2 )     consequent-2 ;```
Where did the alternate statement go? The alternate is the following if statement! But note that the consequent-2 statement will only execute if the predicate-2 is true. If neither predicate is true, no consequent executes. I think it would be accurate to say that there is no 'default' in this snippet as default implies an 'if-all-else-fails' notion.

Code:

```  if( predicate-1 )     consequent-1 ;   else if( predicate-2 )     consequent-2 ;   else     alternate ;```
Now we have an if with another if as its alternate, as in the previous snippet, but that second if now has its own alternate. So by now it should be clear that the unconditional else statement is the default. Don't forget though, we only branch to an else if the preceding predicate was false.