Switch statement is used to solve multiple option type problems for menu like program, where one value is associated with each option.
The expression in switch case evaluates to return an integral value, which is then compared to the values in different cases, where it matches that block of code is executed, if there is no match, then default block is executed.
The general form of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
}
//Write a C Program which demonstrate use switch statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,choice;
clrscr();
while(choice!=3)
{
printf("\n 1. Press 1 for Addition");
printf("\n 2. Press 2 for Subtraction");
printf("\n Enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers:");
scanf("%d%d",&a,&b);
c=a+b;
printf("Addition is %d",c);
break;
case 2:
printf("Enter 2 numbers:");
scanf("%d%d",&a,&b);
c=a-b;
printf("Subtraction is %d",c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
getch();
}
Ask Question