Here is a C program to make a simple calculator to add, subtract, multiply and divide two numbers using switch statement.
This program first takes two integer operands and an arithmetic operator as input from user. The operator is stored in a character variable 'operator'. Only addition, subtraction, multiplication and division(+, - , * and /) operators are allowed, for any other operator it prints error message on screen. It uses switch case statement to perform a particular arithmetic operation based on the 'operator' variable. If none of the operator matches with the input operator then it prints an error message on screen.
C program for simple calculator using switch statement
#include<stdio.h> int main() { char operator; float num1,num2; printf("Enter two numbers as operands\n"); scanf("%f%f", &num1, &num2); printf("Enter an arithemetic operator(+-*/)\n"); scanf("%*c%c",&operator); switch(operator) { case '+': printf("%.2f + %.2f = %.2f",num1, num2, num1+num2); break; case '-': printf("%.2f - %.2f = %.2f",num1, num2, num1-num2); break; case '*': printf("%.2f * %.2f = %.2f",num1, num2, num1*num2); break; case '/': printf("%.2f / %.2f = %.2f",num1, num2, num1/num2); break; default: printf("ERROR: Unsupported Operation"); } return 0; }Output
Enter two numbers as operands 9 3 Enter an arithemetic operator(+-*/) + 9.00 + 3.00 = 12.00
Enter two numbers as operands 5.0 3 Enter an arithemetic operator(+-*/) * 5.00 * 3.00 = 15.00
Related Topics