In: Computer Science
In what situation would you prefer to implement several alternative logical branches using Multi-Way if/else statements? When would you prefer to use Switch?
Greetings!!!!!
Please find my answer as below.
Firstly the major difference between Multi-Way if/else statements and Switch statements are as below.
Multi-way if else Statement |
Switch Statement |
|
Testing Condition |
Multi-way if-else Statement can be used to test the condition on the range of values. |
Switch statement can be used to test the condition on single integer, enumerated value, character, and string object. |
Speed of Execution |
If selection is there among large group of values then Multi-way if else is slower. |
If selection is there among large group of values then switch is faster. |
Suitability |
Multi-way if-else Statement is better for checking range of values. |
Switch statement is better for checking fixed values. |
Number of expressions |
Multi-way if-else Statement has multiple numbers of expressions to be evaluated. |
Switch statement has a single expression to be evaluated. |
Decision making |
In case Multi-way if-else statement, decisions are made on Boolean result of each expression. |
In case of switch statement, decisions are made on equality of fixed value with expression value. |
Entering in blocks |
Multi-way if-else Statement checks for true condition and executes only corresponding block of statements for found true condition. Once executed control comes out of the entire statement. |
Switch statement checks for the first matching and executes statements corresponding to that block and the blocks further below to it until an explicit statement is used to exit entire statement. |
Now the typical syntax of both statements are as below.
Multi-Way if/else statements:---
if( condition-1)
block of statement(s)-1;
else if (condition-2)
block of statement(s)-2;
else if (condition-3)
block of statement(s)-3;
else if (condition-4)
block of statement(s)-4;
else if (condition-n)
block of statement(s)-n;
else
default block of statement(s);
Switch statements:----
switch(expression)
{
case constant-1
block of statement(s)-1;
break;
case constant-2
block of statement(s)-2;
break;
case constant-3
block of statement(s)-3;
break;
case constant-n
block of statement(s)-n;
break;
default:
default_block of statement(s)-;
}
When to use Multi-Way if/else statement----
1) When you need to check range of values in the form of Boolean expression.
2) When number of cases to be checked are less in number.
3) When only one block of statements to be executed.
When to use switch statement-----
1) When you need to check equality of particular expression value.
2) When number of cases to be checked are large in number.
3) When you need to execute multiple of statements after a match is found.
Thank You