C - Switch on char value

Introduction

The following switch statement is controlled by a variable of type char.

The char is entered by the user.

You'll prompt the user to enter the value 'y' or 'Y' for one action and 'n' or 'N' for another.

Demo

#include <stdio.h>

int main(void)
{
  char answer = 0;       // Stores an input character

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

  switch (answer)
  {/*from w w w . j  a va  2s .  c om*/
  case 'y': case 'Y':
    printf("You responded in the affirmative.\n");
    break;

  case 'n': case 'N':
    printf("You responded in the negative.\n");
    break;
  default:
    printf("You did not respond correctly. . .\n");
    break;
  }
  return 0;
}

Result

how It Works

The following three lines define a char type variable and read user input.

char answer = 0;                // Stores an input character

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

The switch statement uses the character stored in answer to select a case:

switch(answer)
{
      . . .
}

The first case in the switch verifies an uppercase or a lowercase letter Y:

case 'y': case 'Y':
      printf("You responded in the affirmative.\n");
      break;

Both values 'y' and 'Y' will result in the same printf() being executed.

If the character entered doesn't correspond with any of the case values, the default case is selected:

default:
      printf("You did not respond correctly. . .\n");
      break;

Related Topic