Simple Calculator Program in C

A simple calculator combines input, arithmetic operators and decision logic. This example lets the user choose addition, subtraction, multiplication or division.

Calculator with switch Top ↑

#include <stdio.h>

int main(void) {
    double first;
    double second;
    char operation;

    printf("Enter an expression such as 12.5 + 3: ");
    if (scanf("%lf %c %lf", &first, &operation, &second) != 3) {
        printf("Invalid input.\n");
        return 1;
    }

    switch (operation) {
        case '+':
            printf("Result = %.2f\n", first + second);
            break;
        case '-':
            printf("Result = %.2f\n", first - second);
            break;
        case '*':
            printf("Result = %.2f\n", first * second);
            break;
        case '/':
            if (second == 0.0) {
                printf("Cannot divide by zero.\n");
                return 1;
            }
            printf("Result = %.2f\n", first / second);
            break;
        default:
            printf("Unknown operator.\n");
            return 1;
    }

    return 0;
}

Same Idea with if...else Top ↑

if (operation == '+') {
    result = first + second;
} else if (operation == '-') {
    result = first - second;
} else if (operation == '*') {
    result = first * second;
} else if (operation == '/') {
    /* check second != 0 before dividing */
}

For exact single-character choices, switch is often easier to scan. Range-based conditions still belong in if...else.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer