C - Associate several case values with one group of statements.

Introduction

You can use an expression that results in a value of type char as the control expression for a switch.

Suppose you read a character into a variable, ch, of type char.

You can classify this character in a switch like this:

Demo

#include <stdio.h>
#include <ctype.h>
int main()//from w  ww .j ava2  s  .co m
{

  char ch = 'a';
  switch (tolower(ch))
  {
  case 'a': case 'e': case 'i': case 'o': case 'u':
    printf("The character is a vowel.\n");
    break;
  case 'b': case 'c': case 'd': case 'f': case 'g': case 'h': case 'j': case 'k':
  case 'l': case 'm': case 'n': case 'p': case 'q': case 'r': case 's': case 't':
  case 'v': case 'w': case 'x': case 'y': case 'z':
    printf("The character is a consonant.\n");
    break;
  default:
    printf("The character is not a letter.\n");
    break;
  }

  return 0;
}

Result

Because you use the function tolower() that is declared in the ctype.h header file to convert the value of ch to lowercase, you only need to test for lowercase letters.

Related Topic