Friday, May 19, 2017

Switch Case

Hi all, today we are going to talk about switch case. Switch case handles the multiple if...else if statements more efficiently.


Figure 1

As shown in the figure, the interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used. The break statement indicate in end of every case. When the suitable case is found out, the code in that block is executed and then break. Therefore other cases are not checked.

Syntax
switch (expression)
{
   case condition 1: 
   statement(s)
   break;
   
   case condition 2: 
   statement(s)
   break;
   ...
   
   default: 
   statement(s)

}

The following example is about switch case.

Example 1


Figure 2

In here, Ann is assigned to the variable 'name'. switch(name)means check variable name is what is equal to. In case 1, variable 'name' is checked that whether it is equal to 'Nick'. Since it is not equal to 'Nick' codes of that case are not executed and then name is checked that whether it is equal to 'Mickey' and it is also not equal. So then  in next case, variable 'name' is checked whether it is equal to 'Ann'. They are equal. So the codes of that case is executed and end of the code break statement is done. So, cases after this case are not checked, therefore the time is saved.
The result is follows.

 Figure 3

Hope you will use switch case in better way and thank you for watching this tutorial.

No comments:

Post a Comment