C - Switch on uppercase char value

Introduction

You can use the toupper() or tolower() function to simplify the cases in the switch.

By using one or the other you can nearly halve the number of cases:

Demo

#include <stdio.h>
#include <ctype.h>
int main(void)
{
  char answer = 0;       // Stores an input character

  printf("Enter Y or N: ");
  scanf(" %c", &answer);


  switch (toupper(answer))
  {/* www . j av a 2  s. c o m*/
  case 'Y':
    printf("You responded in the affirmative.\n");
    break;
  case 'N':
    printf("You responded in the negative.\n");
    break;
  default:
    printf("You did not respond correctly. . .\n");
    break;
  }
  return 0;
}

Result

Related Topic