Simple calculator program in c; Through this tutorial, we will learn how to create simple calculator program in c programming language using switch case and if else statement.
Programs for Simple Calculator in C
- C Program for Simple Calculator using Switch Case
- C Program for Simple Calculator using If else
C Program for Simple Calculator using Switch Case
#include <stdio.h> int main() { char op; double first, second; printf("Enter an operator (+, -, *, /): "); scanf("%c", &op); printf("Enter first numbers: "); scanf("%lf", &first); printf("Enter second numbers: "); scanf("%lf", &second); switch (op) { case '+': printf("%.1lf + %.1lf = %.1lf", first, second, first + second); break; case '-': printf("%.1lf - %.1lf = %.1lf", first, second, first - second); break; case '*': printf("%.1lf * %.1lf = %.1lf", first, second, first * second); break; case '/': printf("%.1lf / %.1lf = %.1lf", first, second, first / second); break; // operator doesn't match any case constant default: printf("Error! operator is not correct"); } return 0; }
The output of the above c program; as follows:
Enter an operator (+, -, *, /): + Enter first numbers: 5 Enter second numbers: 2 5.0 + 2.0 = 7.0
C Program for Simple Calculator using If else
#include <stdio.h> int main() { char Operator; float num1, num2, result = 0; printf("\n Please Enter an Operator (+, -, *, /) : "); scanf("%c", &Operator); printf("\n Please Enter the Values for two Operands: num1 and num2 : "); scanf("%f%f", &num1, &num2); if(Operator == '+') { printf("\n The result of %.2f + %.2f = %.2f", num1, num2, num1 + num2); } else if(Operator == '-') { printf("\n The result of %.2f - %.2f = %.2f", num1, num2, num1 - num2); } else if(Operator == '*') { printf("\n The result of %.2f * %.2f = %.2f", num1, num2, num1 * num2); } else if(Operator == '/') { printf("\n The result of %.2f / %.2f = %.2f", num1, num2, num1 / num2); } else { printf("\n You have enetered an Invalid Operator "); } return 0; }
The output of the above c program; as follows:
Please Enter an Operator (+, -, *, /) : * Please Enter the Values for two Operands: num1 and num2 : 5 2 The result of 5.00 * 2.00 = 10.00