SWITCH CASE

Switch case changes the direction of flow of control with respect to the input. The condition in switch statement is compared with case statements in the switch block.when the switch condition and case condition both are equal, the statements in that specific case block are executed.

Using default statement is optional but it is preferred to handle errors when switch condition does not matches with any of the case conditions.


Therefore, the statements in the default block executes only if the switch condition does not matches with any of the case conditions.
Using break statement is optional.

Note: If there is no break statement in case blocks then after executing the necessary  case block instead of exiting the switch block compiler executes all other case block which are followed by the necessary case block. We should use break statement in each case block in order to prevent the flow of control in entering into next case block. 

FLOW CHART

Syntax :
 switch(choice_variable){
          case case_variable-1:          Statements-A;
          break;

          case case_variable-2:

          Statements-B;
          break;
          .
          .
          .
          case case_variable-n:
          Statements;
          break;
           
          default:
          Statements;}

EXAMPLE CODE:

OUTPUT

Leave a Reply