Write a C program to make a simple calculator using switch

Description: Take two numbers and an operator (+, -, *, /) as input. Print the result.

Hint:

  • Use a switch on the operator character. Check that the divisor is not zero before dividing.

C program for a simple calculator

#include <stdio.h>

int main(void) {
    float a, b;
    char op;

    printf("Enter number, operator, number: ");
    scanf("%f %c %f", &a, &op, &b);

    switch (op) {
        case '+': printf("Result = %.2f\n", a + b); break;
        case '-': printf("Result = %.2f\n", a - b); break;
        case '*': printf("Result = %.2f\n", a * b); break;
        case '/':
            if (b != 0) {
                printf("Result = %.2f\n", a / b);
            } else {
                printf("Division by zero is not allowed\n");
            }
            break;
        default:
            printf("Invalid operator\n");
    }
    return 0;
}

Output:

Output of the above program is

Enter number, operator, number: 12 / 5
Result = 2.40

How it works

  • The input 12 / 5 is read into a, op and b.
  • The case '/' runs and prints 2.40.
  • The default case handles any other character.

Read C Switch Statement.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.