Simple Calculator
A calculator combines a selected operation with branching and arithmetic.
What is Simple Calculator?
A calculator combines a selected operation with branching and arithmetic.
Apply an arithmetic operator to two numbers.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int left = 12, right = 4, result = 0; char operation = '*';
// Select the calculation from the operator.
switch (operation) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; }
printf("%d %c %d = %d\n", left, operation, right, result);
}
12 * 4 = 48
C++
main.cpp
#include <iostream>
int main() {
int left = 12, right = 4, result = 0; char operation = '*';
// Select the calculation from the operator.
switch (operation) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; }
std::cout << left << ' ' << operation << ' ' << right << " = " << result << '\n';
}
12 * 4 = 48
C and C++ comparison
The switch dispatches one character to the corresponding operation and keeps each case explicit.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.