Menu

Switch Statement in C

  • If a programmer has to choose one block of statement among many alternatives, this type of problem can be handled in C programming using the switch statement.
  • When a number of actions are to be taken based on a number of different conditions, the switch statement is the better selection statement.

Syntax

     Switch (Expression) { 
        case Constant 1 : Statement Sequence 1;break;
        case Constant 2 : Statement Sequence 2;break; 
        case Constant 3 : Statement Sequence 3;break; 
        ......................................
        case ConstantN-1 : Statement SequenceN-1;break; 
        deafault : StatementSequenceN; 
    }

Syntax

    #include
    main(){
        int n;
        printf("enter your choice:");
        scanf("%d",&n);
        switch(n){
            case 1:printf("you are selected the first case");break;
            case 2:printf("you are selected the second case");break;
            case 3:printf("you are selected the third case");break;
            case 4:printf("you are selected the fourth case");break;
            case 5:printf("you are selected the fifth case");break;
            case 6:printf("you are selected the sixth case");break;
            case 7:printf("you are selected the seventh case");break;
            default:printf("invalid input");
        }
     }

Output

         enter your choice:3

         you are selected the third case

Sample Programs

  • C program to select a day in a week using the switch statement
  • C program to perform arithmetic calculations.