ITDeveloper : C Programming
C Programming
Step by Step Tutorials
![]() Share with a Friend |
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases).
- Switch case statements follow a selection-control mechanism and allow a value to change control of execution.
- They are a substitute for long if statements that compare a variable to several integral values.
- The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
In C, the switch case statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.
Syntax of switch Statement in C
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}
Rules of the switch case statement
Following are some of the rules that we need to follow while using the switch statement:
- In a switch statement, the “case value” must be of “char” and “int” type.
- There can be one or N number of cases.
- The values in the case must be unique.
- Each statement of the case can have a break statement. It is optional.
- The default Statement is also optional.
Flowchart of Switch Statement
Example: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>
int main() {
char op;
int n1, n2;
printf("Enter first operand: ");
scanf("%d",&n1);
printf("Enter second operand: ");
scanf("%d",&n2);
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
switch(op)
{
case '+\:
printf("%d + %d = %d",n1, n2, n1+n2);
break;
case '-':
printf("%d - %d = %d",n1, n2, n1-n2);
break;
case '*':
printf("%d * %d = %d",n1, n2, n1*n2);
break;
case '/':
printf("%d / %d = %d",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! Wrong Operator ");
}
return 0;
}
OUTPUT 1:
Enter first operand: 5
Enter second operand: 6
Enter an operator (+, -, *, /): +
11
OUTPUT 2:
Enter first operand: 5
Enter second operand: 6
Enter an operator (+, -, *, /): *
30