C Program to Make a Simple Calculator
Last Updated :
17 Jul, 2023
A calculator is an electronic device that is used to perform arithmetic operations like addition, subtraction, multiplication, division, etc. We can create a simple calculator program in C to perform all these basic calculations. In this article, we will see how to create a simple calculator in C using the switch statement.
This program takes an arithmetic operator (+, -, *, /) and two operands as the input. It then checks whether the user wants to quit the program if yes then quit it, for this, we can use a special character and tell the user about it, like here we used “x”. The operation is performed based on the operator.
Approach
- All the following steps will be performed inside a never-ending loop so that the calculator program keeps on working.
- Take input of operator and then operands.
- Check whether the user wants to quit the program if yes then quit it, for this, we can use a special character and tell the user about it, like here we used “x”.
- Using if-else statements we will check operators and do operations accordingly.
Simple Calculator Program using switch Statement
Below is the C program to implement a simple calculator using a switch case statement:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
double a, b;
while (1) {
printf ( "Enter an operator (+, -, *, /), "
"if want to exit press x: " );
scanf ( " %c" , &ch);
if (ch == 'x' )
exit (0);
printf ( "Enter two first and second operand: " );
scanf ( "%lf %lf" , &a, &b);
switch (ch) {
case '+' :
printf ( "%.1lf + %.1lf = %.1lf\n" , a, b, a + b);
break ;
case '-' :
printf ( "%.1lf - %.1lf = %.1lf\n" , a, b, a - b);
break ;
case '*' :
printf ( "%.1lf * %.1lf = %.1lf\n" , a, b, a * b);
break ;
case '/' :
printf ( "%.1lf / %.1lf = %.1lf\n" , a, b, a / b);
break ;
default :
printf (
"Error! please write a valid operator\n" );
}
printf ( "\n" );
}
}
|
Output
Enter an operator (+, -, *, /), if want to exit press x: +
Enter two first and second operand: 7 8
7.0 + 8.0 = 15.0
Enter an operator (+, -, *, /), if want to exit press x: -
Enter two first and second operand: 8 9
8.0 - 9.0 = -1.0
Enter an operator (+, -, *, /), if want to exit press x: *
Enter two first and second operand: 8 7
8.0 * 7.0 = 56.0
Enter an operator (+, -, *, /), if want to exit press x: /
Enter two first and second operand: 8 3
8.0 / 3.0 = 2.7
Enter an operator (+, -, *, /), if want to exit press x: x
Complexity Analysis
- Time Complexity: O(1)
- Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...