Flowchart illustrating the step-by-step logic and execution flow of a C switch-case statement with expressions and case labels.

This Diagram is about the flowchart for a switch-case statement. And now let's study how the switch-case statement works in a stepwise manner by just following the logic in the figure. In the very beginning, the exp (expression) that has been mentioned in the switch-case is evaluated. This expression will be evaluated just once before comparing its resultant value against the constant values of all the case labels (like case 1, case 2, and so forth or with default label).

If a match is found (for example if the expression matches case constant1), such statements will become executed inside the respective case block. Execution will continue until a break statement is traversed. The activity of a break statement is to stop immediately the execution of the switch block and transfer the control to the code directly after the switch block. In case no match is found within all these case options, the default case (if you have included it) will execute. At the end of the default case, the control automatically exits the switch statement.


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.


Other Topics
SQL Interview Questions Java Interview QuestionsTop SQL Interview QuestionsPython Interview QuestionsBanking Case Study in SQL