Switch Statement:
A switch statement in C is a control flow statement that allows a program to perform different actions based on the value of an expression. It provides an alternative way to handle multiple conditions more efficiently than a series of nested if-else statements. In Short, The Control statement which allows us to make a decision from the number of choices is called a switch or switch-case-default.
Flow-Chart:
Syntax:
switch (expression) {
case constant1:
// Code to be executed if expression matches constant1
break;
case constant2:
// Code to be executed if expression matches constant2
break;
// Additional cases as needed
default:
// Code to be executed if none of the cases match
}
Here’s how the switch statement works:
- The switch keyword is followed by an expression (often a variable or a value).
- The expression is evaluated, and its value is compared to each case constant.
- If a match is found, the code associated with that case is executed.
- The break statement is used to exit the switch block. If a break is not present, control will “fall through” to subsequent cases, executing their code as well.
- The default case is optional and provides a default action if none of the cases match.
Example: Program To generate a Calculator using Switch Statement
#include <stdio.h>
int main()
{
char operator;
double num1, num2, result;// Input from the user
printf(“Enter operator (+, -, *, /): “);
scanf(” %c”, &operator); // Note the space before %c to consume any newline character left in the input buffer
printf(“Enter two numbers: “);
scanf(“%lf %lf”, &num1, &num2);// Switch statement to perform the calculation based on the operator
switch (operator)
{
case ‘+’:
result = num1 + num2;
printf(“Result: %.2fn”, result);
break;
case ‘-‘:
result = num1 – num2;
printf(“Result: %.2fn”, result);
break;
case ‘*’:
result = num1 * num2;
printf(“Result: %.2fn”, result);
break;
case ‘/’:
if (num2 != 0)
{
result = num1 / num2;
printf(“Result: %.2fn”, result);
}
else
{
printf(“Error: Division by zero is not allowed.n”);
}
break;
default:
printf(“Error: Invalid operator.n”);
}return 0;
}
Output:
Enter operator (+, -, *, /): *
Enter two numbers: 4
6
Result: 24.00