Use switch statement to check the user input - C Statement

C examples for Statement:switch

Description

Use switch statement to check the user input

Demo Code

#include <stdio.h>

int main(void){
      int choice = 0;            // The number chosen
    //from w w w . j a  va 2 s .co m
      printf("Pick a number between 1 and 10! ");
      scanf("%d", &choice);
    
      if((choice > 10) || (choice < 1))
         choice = 11;             // Selects invalid choice message

      switch(choice)
      {
        case 7:
          printf("seven.\n");
          break;                 // Jumps to the end of the block
    
        case 2:
          printf("two.\n");
          break;                 // Jumps to the end of the block
    
        case 8:
          printf("eight.\n");
          break;                 // Jumps to the end of the block
    
        case 11:
          printf("eleven.\n");
                                 // No break - so continue with the next statement
    
        default:
          printf("default.\n");
          break;                 // Defensive break - in case of new cases
      }
      return 0;
}

Result


Related Tutorials