Programing invloves creating solution for real world problems. In this article we will see how to devlop a simple C program that takes two operends and one operator from user, perform the requested operation and prints the result.
Table of Contents
Problem Statement- WAP that takes two operands and one operator from the user, perform the operation,and prints the result by using Switch statement.
C Program for Calculator Using Switch Statement
In this C program for calculator, we will use switch statements for efficiently handling multiple operations.
#include <stdio.h>
void main()
{
float operand1, operand2, result;
char operator;
printf("Enter operand 1 ");
scanf("%f", &operand1);
printf("Enter operator (+, -, *, /) ");
scanf(" %c", &operator); // the space before %c to consume the newline character
printf("Enter operand 2 ");
scanf("%f", &operand2);
switch (operator)
{
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 == 0)
{
printf("Division by 0 is not possible ");
return;
}
else
{
result = operand1 / operand2;
}
break;
default:
printf("Invalid input");
return;
}
printf("\n%f %c %f = %f", operand1, operator, operand2, result);
}
Output
Explanation of Above C Program
- The program asks the user to enter the first operand, operator, and second operand by using printf and scanf functions.
- The switch statement is used to perform an appropriate operation based on the entered operator. the switch statement efficiently handles multiple cases making the code more readable.
- The above C program also checks for division by 0 when the operator is ‘/’ to avoid undefined behavior.
- The result of the operation is displayed by using the print function.
Happy Coding
2 thoughts on “Calculator Program in C Using Switch Statement”