C Program to Make a Simple Calculator using Switch Statement

  • Write 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

/* 
* C program to create a simple calculator using switch...case statement
*/

#include<stdio.h>
#include<conio.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");
    }
    
    getch();
    return 0;
}
Program 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
C programming switch case statement
C arithmetic operators
C program to find all roots of quadratic equation
C program to convert decimal numbers to binary numbers
C program to print fibonacci series using recursion
C program to reverse a string using recursion
C program to check if two strings are anagram
C Program to calculate factorial of a number
C program to find hcf and lcm of two numbers
C program to find maximum of two numbers using switch statement
C program to print all prime numbers between 1 to N
C Program for matrix multiplication
C star pattern programs
List of all C programs