Menu

Switch Statement In C Programming

  • If a programmer has to choose one block of statement among many alternatives,this type of problem can be handled in C programming using switch statement.
  • When a number of actions are to be taken based on a number of different conditions, 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;
          }

Example

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

OUTPUT

      enter your choice:3
      you are selected third case

Sample Programs

  1. C program to select a day in a week using switch statement
  2. C program to perform arithmetic calculations.