switch case in C programming

Given Diagram is for the flowchart of the switch-case statement.
Let us start learning how switch-case work with the help of flowchart given in the fig.
exp is the integer expression given in the switch statement which evaluates first.
The given exp evaluates only once and compare the values of each case labels.
The integer expression value is then matched one-by-one with constant cases values i.e. case-1,case-2 . . .case-n or default.
If specific match is found, Let say case-1 then stamt-1 inside that case-1 executes till the break statement.
After that break statement executes, the break statement stop executing the remaining statement in the switch and control comes out of switch and continue the reamining statements in programme.
In some situation suppose switch case do not have break in any of the cases , then all the cases executes one by one including default case.
Programmer can not specify more than one cases with similar values.
if mached cases do not contain break statement then all the cases starting from matching case to default case will be executed.
if any of the case encounter the break statement it will come out of switch and rest of the cases will be skipped.
Otherwise all the cases after matched case will be executed one by one.
default case will be processed when switch do not find any maching case.


Example 1: C program using switch case to create a simple calculator.

// Program to create a simple Choice base calculator in C Language using switch case
#include <stdio.h>
int main()
{
char operation;
double a, b;

printf("\n Addition: +");
printf("\n Substraction: -");
printf("\n Multiplication: *");
printf("\n Division: /");

printf("Enter Your choice or an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter two Values: ");
scanf("%lf %lf",&a, &b);
switch(operation)
{
  case '+':
   printf("\nAddition=>%.1lf + %.1lf = %.1lf",a, b, (a+b));
   break;
  case '-':
    printf("\nSubstaction=>%.1lf - %.1lf = %.1lf",a, b, (a-b));
    break;
 case '*':
   printf("\n Multiplication=>%.1lf * %.1lf = %.1lf",a, b, (a*b));
   break;
 case '/':
    printf("\nDivision=>%.1lf / %.1lf = %.1lf",a, b, (a/b));
   break;
 /* operator doesn't match any case constant +, -, *, /   */
 default:
    printf("Error! Wrong choice or operator try again....");
}
return 0;
}


Output:
Addition: +
Substraction: -
Multiplication: *
Division: /

Enter Your choice or an operator (+, -, *, /):
-
Enter two Values: 52.5
12.3
Substaction=>52.5 - 12.3 = 40.2


Previous Topic:-->> Nested if else statement in C || Next topic:-->>C Decision Making Assignments.