C – switch statement

After reading this C switch statement topic, you will understand the switch statement syntax and you will know the flowchart, theory, and examples.

In real life, most of the situations are dealt with many alternatives and we have to choose any one among them, is the logic of the switch statement.

switch statement also called multi-way statement i.e. to execute statement(s) under one choice out of many choices.

General Form (Syntax):

The syntax of switch statement is given below,

switch (expression)
{ 
case value1:
statement(s);
break; 
case value2:
statement(s);
break;
.
.
.
default:
statement(s);
break;
}

When expression evaluates to match value1, the switch statement executes case value1 statement(s) until break statement met and skip remaining case statement(s).
When expression evaluates to match value2, the switch statement executes case value2 statement(s) until break statement met and skip remaining case statement(s).
When expression evaluates to not match any of the value (i.e. value1, value2, …), the switch statement executes default statement(s) until break statement as well as skips all case statement(s).
The expression can be either integer or character and the value (i.e. value1, value2, …) need not be in any particular order but must be either constant or constant expression. The keyword break used to terminate the switch statement.

switch statement flowchart:

The flow chart of the switch statement is given below,

Example:
Program (1): To enter a choice by the user for playing one game out of Cricket, Football, and Hockey, using the switch statement.

#include<stdio.h>
#include<conio.h>
void main(void)
{
int i;
printf("enter your choice,1 for playing Cricket, 2 for playing Football, 3 for playing Hockey : n");
scanf("%d",&i);
switch ( i )
{
case 1 :
printf ( "you will play Cricket n" ) ;
break ;
case 2 :
printf ( "you will play Football n" ) ;
break ;
case 3 :
printf ( "you will play Hockey n" ) ;
break ;
default :
printf ( "enter choice is not valid n" ) ;
}
getch();
}

Output (1)

enter your choice,1 for playing Cricket, 2 for playing Football, 3 for playing Hockey :
2
you will play Football

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *