Introduction to Programming - (C Language) - Unit : 2 - Switch statement
C SWITCH STATEMENT
The switch statement in C
language is used to execute the code from multiple conditions. It is like if else-if ladder statement.
The syntax of switch
statement in c language is given below:
switch(expression)
{
case value1:
{
//code to be executed;
break; //optional
}
case value2:
{
//code to be executed;
break; //optional
}
Case
value3:
{
//code to be executed;
break; //optional
}
default:
{
code to be executed if all cases are not matched;
}
Rules for switch statement in C language
1) The switch expression must be of integer or
character type.
2) The case value must be integer or
character constant.
3) The case value can be used only inside the
switch statement.
4) The break statement in switch case is not must.
It is optional. If there is no break statement found in switch case, all the
cases will be executed after matching the case value. It is known as fall through state of C switch
statement. Flowchart of switch statement in C
Let's see a simple
example of c language switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
switch(number)
{
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
getch();
}
Output
Enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
Programs on switch case
1. ATM P
Comments
Post a Comment