Table of Contents
show
Switch statement
- A switch statement is used to control complex branching operations
- When there are many conditions, it becomes too difficult and complicated to use if and if-else constructs.
- In such case, the switch statement provides an easy and organized way to select among multiple operations, depending upon the outcome of a particular condition.
The general form of switch statement is
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Flowchart
Example
Calculator Program using switch case
#include<stdio.h>
int main()
{
int choice;
int num1,num2;
printf("Enter two numbers \n");
scanf("%d%d", &num1, &num2);
printf("1.Addition\n");
printf("2.Subtraction\n");
printf("3.Multiplication\n");
printf("4.Division\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("%d + %d = %d",num1, num2, num1+num2);
break;
case 2:
printf("%d - %d = %d",num1, num2, num1-num2);
break;
case 3:
printf("%d * %d = %d",num1, num2, num1*num2);
break;
case 4:
printf("%d / %d = %.2f",num1, num2, num1/num2);
break;
default:
printf("ERROR:");
}
return 0;
}
Output
Enter two numbers
3 4
1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter your choice
2
3 - 4 = -1
Views: 0