It is used to select one among multiple decisions. ‘switch’ successively tests a value against a list of integers (or) character constant. When a match is found, the statement (or) statements associated with that value are executed.
Syntax
The syntax is given below −
switch (expression){ case value1 : stmt1; break; case value2 : stmt2; break; - - - - - - default : stmt – x; }
Algorithm
Refer the algorithm given below −
Step 1: Declare variables. Step 2: Read expression variable. Step 3: Switch(expression) If value 1 is select : stmt 1 executes break (exists from switch) If value 2 is select : stmt 2 executes ;break If value 3 is select : stmt 3 executes; break …………………………………………… Default : stmt-x executes;
Example
The following C program demonstrates the usage of switch statement −
#include<stdio.h> main ( ){ int n; printf ("enter a number"); scanf ("%d", &n); switch (n){ case 0 : printf ("zero"); break; case 1 : printf ("one"); break; default : printf ("wrong choice"); } }
Output
You will see the following output −
enter a number 1 One
Consider another program on switch case as mentioned below −
Example
#include<stdio.h> int main(){ char grade; printf("Enter the grade of a student:\n"); scanf("%c",&grade); switch(grade){ case 'A': printf("Distiction\n"); break; case 'B': printf("First class\n"); break; case 'C': printf("second class \n"); break; case 'D': printf("third class\n"); break; default : printf("Fail"); } printf("Student grade=%c",grade); return 0; }
Output
You will see the following output −
Run 1:Enter the grade of a student:A Distiction Student grade=A Run 2: Enter the grade of a student:C Second class Student grade=C