← Back to the course

A TEACHING EXAMPLE · C PROGRAMMING

A calculator you can explain.

Two numbers, one operation, a result. Try the behavior here, then build the C program on your computer.

Try the interaction

12 + 8 = 20

This browser demo uses JavaScript to show the expected behavior. The C source below runs separately with a compiler.

BUILD IT YOURSELF

Understand each step.

  1. Read two numbers and an operator. Reject input that does not match.
  2. Choose the operation with a switch statement.
  3. Handle division by zero before performing division.
  4. Print the result and test all four operations.
Download example source

Save as calculator.c. Build: gcc -Wall -Wextra -pedantic calculator.c -o calculator. Run ./calculator, or calculator.exe on Windows.

Read the C source
/* Local teaching example: gcc -Wall -Wextra -pedantic calculator.c -o calculator */
#include <stdio.h>
#include <math.h>

int main(void) {
    double first, second, result;
    char operation;
    printf("Enter an expression, for example 12 + 8: ");
    if (scanf("%lf %c %lf", &first, &operation, &second) != 3 ||
        !isfinite(first) || !isfinite(second)) {
        fprintf(stderr, "Enter two finite numbers and an operator.\n");
        return 1;
    }
    switch (operation) {
        case '+': result = first + second; break;
        case '-': result = first - second; break;
        case '*': result = first * second; break;
        case '/':
            if (second == 0.0) {
                fprintf(stderr, "Cannot divide by zero.\n");
                return 1;
            }
            result = first / second;
            break;
        default:
            fprintf(stderr, "Supported operators: + - * /\n");
            return 1;
    }
    if (!isfinite(result)) {
        fprintf(stderr, "Result is outside the supported range.\n");
        return 1;
    }
    printf("Result: %.12g\n", result);
    return 0;
}