C Example Code2026-03-202 min read
Build a command-line calculator in C using switch-case statements, arithmetic operators, division-by-zero checks, and modular functions.
Calculator Logic & Input Handling
A basic calculator accepts two operands and an operator character (+, -, *, /, %) and evaluates the expression cleanly using a C switch statement.
C Source Code
c (ISO Standard)#include <stdio.h> #include <stdbool.h> bool calculate(double num1, char op, double num2, double *result) { switch (op) { case '+': *result = num1 + num2; return true; case '-': *result = num1 - num2; return true; case '*': *result = num1 * num2; return true; case '/': if (num2 == 0.0) { printf("Error: Division by zero is undefined.\n"); return false; } *result = num1 / num2; return true; default: printf("Error: Unsupported operator '%c'.\n", op); return false; } } int main() { double a = 24.0, b = 6.0; char operators[] = {'+', '-', '*', '/', '?'}; int count = sizeof(operators) / sizeof(operators[0]); printf("Executing Calculator Operations in C:\n\n"); for (int i = 0; i < count; i++) { char op = operators[i]; double res; if (calculate(a, op, b, &res)) { printf(" %.1f %c %.1f = %.2f\n", a, op, b, res); } } return 0; }
Sample Output
text (ISO Standard)Executing Calculator Operations in C: 24.0 + 6.0 = 30.00 24.0 - 6.0 = 18.00 24.0 * 6.0 = 144.00 24.0 / 6.0 = 4.00 Error: Unsupported operator '?'.
Complexity Analysis
- Time Complexity:
O(1)constant time arithmetic. - Space Complexity:
O(1)zero auxiliary memory.
Related References
- Review arithmetic precedence in C Operators Reference.
- Learn conditional control flow in C Programming Basics.