In C programming language, sometimes we need to check multiple conditions. At that time we can you switch...case statement.
Syntax:
switch(choice)
{
case value1:
statement-1;
break;
case value2:
statement-2;
break;
case value3:
statement-3;
break;
case value4:
statement-4;
break;
.
.
.
.
.
case value-n:
statement-n;
break;
default:
default statement;
}
Example: A C Program to add, subtract, multiply, divide two values using switch...case statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum,sub,mult,div,choice;
clrscr();
printf("Enter the value of a:");
scanf("%d",&a);
printf("\n Enter the value of b:");
scanf("%d",&b);
printf("\n select your choice from following list:-");
printf("\n press 1 for addition.");
printf("\n press 2 for subtraction");
printf("\n press 3 for multiplication");
printf("\n press 4 for division");
printf("\n\n Please enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("\n sum = %d",sum);
break;
case 2:
sub:a-b;
printf("\n sub = %d",sub);
break;
case 3:
mult=a*b;
printf(“\n multi = %d”,mult);
break;
case 4:
div=a/b;
printf(“\n div = %d”,div);
default:
printf(“\n Invalid Choice...!!”);
}
getch();
}
Syntax:
switch(choice)
{
case value1:
statement-1;
break;
case value2:
statement-2;
break;
case value3:
statement-3;
break;
case value4:
statement-4;
break;
.
.
.
.
.
case value-n:
statement-n;
break;
default:
default statement;
}
Example: A C Program to add, subtract, multiply, divide two values using switch...case statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum,sub,mult,div,choice;
clrscr();
printf("Enter the value of a:");
scanf("%d",&a);
printf("\n Enter the value of b:");
scanf("%d",&b);
printf("\n select your choice from following list:-");
printf("\n press 1 for addition.");
printf("\n press 2 for subtraction");
printf("\n press 3 for multiplication");
printf("\n press 4 for division");
printf("\n\n Please enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("\n sum = %d",sum);
break;
case 2:
sub:a-b;
printf("\n sub = %d",sub);
break;
case 3:
mult=a*b;
printf(“\n multi = %d”,mult);
break;
case 4:
div=a/b;
printf(“\n div = %d”,div);
default:
printf(“\n Invalid Choice...!!”);
}
getch();
}
RELATED TOPICS |
---|
Simple if statement. |
if...else statement. |
if...else if ladder(multiple if else). |
Very informative blog!
ReplyDeletePlease take some time to visit my blog @
loop in C notes
Thanks!