Switch Case Statement

The switch statement is a multiway branch statement. It provides the easyest way to dispatch the execution to different parts of the codes based on the value of expression. Switch is a control statement that allows a value to change the control of execution. The switch statement allows us to execute one code block among the all alternative blocks. You can do the same thing with the if...else..if statement but the syntax of the switch case statement is much easier to read and write. See the following diagram.

flowchart example

Keynotes about switch case:

  1. Duplicate case values are not allowed.
  2. The default statement is optional but if the switch case statement do not have a default statement, it would run without any problem.
  3. The break statement is used inside the blocks to terminate a statement sequence. When compiler get break statement the switch terminate , and the compiler jumps to the next line following the switch statement.
  4. Nested of switch statements are allowed which means you can have a switch statements inside a another switch. However nested switch statements should be avoided because it makes program more complex and less readable.
example1:
#include<stdio.h>
int main(){
  int x=2;
  switch (x) { 
       case 1: printf("Choice is 1"); 
               break; 
       case 2: printf("Choice is 2"); 
                break; 
       case 3: printf("Choice is 3"); 
               break; 
       default: printf("Choice other than 1, 2 and 3"); 
                break;   
   } 
   return 0;
}

Output:
  Choice is 2

example2:
    #include<stdio.h>
    int main(){
      int x=5;
      switch (x) { 
           case 1: printf("Choice is 1"); 
                   break; 
           case 2: printf("Choice is 2"); 
                    break; 
           case 3: printf("Choice is 3"); 
                   break; 
           default: printf("Choice other than 1, 2 and 3"); 
                    break;   
       } 
       return 0;
    }

Output:
      Choice other than 1, 2 and 3
Best way of learing

Self learing is the best learing in the world. Discover yourself first then will get what you are And what you want to do .It will push you for self learing.

Why you need to learn coding?

Coding will play a vital role in one's life . It will help to open a new window of thinking . You can think better way than past . It helps to organise all the thing in better way .