A simple calculator combines input, arithmetic operators and decision logic. This example lets the user choose addition, subtraction, multiplication or division.
#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;
}
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.