C Program to Make a Simple Calculator - Switch‑Case Operations

Simple Calculator Using Switch Statement

#include <stdio.h>

int main() {
    double num1, num2;
    char op;

    printf("Enter an operator (+, -, *, /, %c): ", '%');
    scanf(" %c", &op);

    printf("Enter two numbers: ");
    scanf("%lf %lf", &num1, &num2);

    switch (op) {
        case '+':
            printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
            break;
        case '-':
            printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
            break;
        case '*':
            printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
            break;
        case '/':
            if (num2 == 0) {
                printf("Error! Division by zero is not allowed.\n");
            } else {
                printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
            }
            break;
        case '%':
            // Modulus works on integers, cast the numbers
            printf("%d %% %d = %d\n", (int)num1, (int)num2, (int)num1 % (int)num2);
            break;
        default:
            printf("Error! Operator not supported.\n");
    }

    return 0;
}
Enter an operator (+, -, *, /, %): *
Enter two numbers: 7.5 4
7.5 * 4 = 30.00
        

This calculator asks the user to choose an operator and then enter two numbers. A switch statement performs the selected arithmetic operation. Note how division by zero is checked before attempting the calculation. Modulus requires integer operands, so casting is used when computing %.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗