Objective-C: Switch statement

Switch is a control statement that is used when random selection is required at an instance. When value of a variable controls the execution of statements in a program, replacing long conditional statements or, when required to select a certain condition from a set of conditions.

Syntax:

        switch (expression/variable)

             {

                case variable1:

                                                                             ……..Statements;  

                                        ……..

                                        break;

                case variable2:

                                        …….

                                        ……..Statements;  

                                        ……..

                                        break;

                 .

                 .

                 .

                case variable_n:

                                        …….

                                        ……..Statements;  

                                        ……..

                                        break;

             

               default:  

                             statements;

            } 

 

As the program counter enters switch, it evaluates the expression inside and the program counter moves to the corresponding value of the case, if no value of the case matches switch expression, the default case is executed. The break statement is used after every case so that the control jumps out of switch after the execution of the statements inside the case. If break is not used than all the cases from the value that matches the expression will be executed sequentially including default case.

Program using switch statement.

 

If the value of the switch variable is entered different from the defined cases, the output would be like this:

Output:

press 1 for addition and 2 for subtraction

enter your choice: 5

you have entered wrong value.