C switch…case Statement

In this lesson, you will learn about the switch…case statement in C, its usage, and examples to better understand the topic.

What is the switch…case Statement in C?

Switch… case is identical to the if-then… else control structure. It executes only one block of code depending on the condition’s value. If no condition is encountered, the default code block will be performed.

Syntax of the switch…case in C

switch (var) {

case control1:

  //block of code will be processed if var = control1;

  break;

case control2:

  //block of code will be processed if var = control2;

  break;

case control3:

  //block of code will be processed if var = control3;

  break;

default:

  //block of code will be processed if var is different from all controls;

}

“Switch (…) { … }” is the control structure block code “case value: case …” which is the code blocks to be executed depending on the value that matches the “default” condition value: is the code block to be executed if no value matches the condition.

Flow Chart of Switch Statement

 

Note: Switch Statement without break keyword; all cases will be executed.

Example of the switch…case Statement in C

//C Program *** Switch Statement***
#include <stdio.h>

int main() {
  char luxuryCars;
  printf("Enter the any alphabet to win a car: ");
  scanf("%c", & luxuryCars);
  switch (luxuryCars) {
  case 'A':
    printf("Congratulation!!Your won Audi luxury car!");
    break;
  case 'F':
    printf("Congratulation!!Your won Ferrari luxury car!");
    break;
  case 'V':
    printf("Congratulation!!Your won Volvo luxury car!");
    break;
  default:
    printf("Sorry, better luck next time!");
  }
  return 0;
}

Output

Enter the any alphabet to win a car: F
Congratulation!!Your won Ferrari luxury car!

Don’t miss the break keyword! Below is a similar program, but without the break keyword. You will notice that all cases will be printed out to the output.

//C Program *** Switch without break Statement***
#include <stdio.h>

int main() {
  char luxuryCars;
  printf("Enter the any alphabet to win a car: ");
  scanf("%c", & luxuryCars);
  switch (luxuryCars) {
  case 'A':
    printf("Congratulation!!Your won Audi luxury car!\n");
    //break;
  case 'F':
    printf("Congratulation!!Your won Ferrari luxury car!\n");
    //break;
  case 'V':
    printf("Congratulation!!Your won Volvo luxury car!\n");
    //break;
  default:
    printf("Sorry, better luck next time!");
  }
  return 0;
}

Output

Enter the any alphabet to win a car: A
Congratulation!!Your won Audi luxury car!
Congratulation!!Your won Ferrari luxury car!
Congratulation!!Your won Volvo luxury car!
Sorry, better luck next time!

In the next lesson, you will learn about other essential topics in C Language Programming, Loops!