Arithmetic operations play a fundamental role in computer programming, enabling developers to perform calculations and manipulate numerical data efficiently. In the C programming language, one way to execute arithmetic operations is by utilizing switch-case statements, providing a structured and organized approach to handle different mathematical operations.
Switch Statement in C
The switch case statement in C enables programmers to control the program’s flow based on the value of an expression. It comprises a series of case labels, each associated with a specific code block. When the expression’s value matches a case label, the corresponding code block is executed.
The general syntax of the switch case statement is as follows:
switch (expression) {
case value1:
// Code block for value1
break;
case value2:
// Code block for value2
break;
...
default:
// Default code block
}
Arithmetic Operations Using Switch Case in C – Code
Let’s see how arithmetic operations can be implemented using switch-case statements in C –
#include <stdio.h>
void main() {
char operation;
double num1, num2, result;
// Displaying the menu of arithmetic operations
printf("Choose an arithmetic operation (+, -, *, /, %%): ");
scanf("%c", &operation);
// Input two numbers for the arithmetic operation
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
// Switch-case statement to perform the selected arithmetic operation
switch (operation) {
case '+':
result = num1 + num2;
printf("Sum: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
printf("Difference: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
printf("Product: %.2lf\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Quotient: %.2lf\n", result);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
case '%':
if (num2 != 0) {
result = (int)num1 % (int)num2;
printf("Modulus: %.2lf\n", result);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operation selected.\n");
}
}
This C program starts by prompting the user to select an arithmetic operation from the menu (+, -, *, /, %). Then, it reads two numbers from the user. Based on the selected operation, the switch-case statement performs the corresponding arithmetic calculation and displays the result.
3 thoughts on “Arithmetic Operations Using Switch Case in C”