Building a Simple Calculator with C
Gathering Input
The first step in building our calculator is to gather input from the user. We need to know what operation they want to perform and what two numbers they want to operate on. To do this, we’ll use the scanf
function to read in the operator (+, -, *, /) and two operands.
char op;
double first, second;
scanf(" %c %lf %lf", &op, &first, &second);
The Switch Statement: The Heart of Our Calculator
The switch statement is where the magic happens. We’ll use it to determine which operation to perform based on the operator entered by the user. The syntax is simple:
switch (op) {
case '+':
// addition
break;
case '-':
// subtraction
break;
case '*':
// multiplication
break;
case '/':
// division
break;
default:
printf("Invalid operator\n");
break;
}
Performing Calculations
Once we’re inside the correct case block, we can perform the calculation. For example, for multiplication, we’ll simply multiply the two operands together:
result = first * second;
To make our output look cleaner, we’ll limit the result to one decimal place using the %.1lf
format specifier:
printf("Result: %.1lf\n", result);
Breaking Out
Finally, we’ll use the break
statement to exit the switch block and prevent the program from falling through to the next case. Without break
, our program would continue executing code until it reaches the end of the switch block or encounters another break
statement.
The Final Result
When we run our program, we’ll see the result of the calculation displayed on the screen. With the switch statement, break
, and continue
, we’ve built a simple yet powerful calculator that can perform basic arithmetic operations.
#include <stdio.h>
int main() {
char op;
double first, second, result;
scanf(" %c %lf %lf", &op, &first, &second);
switch (op) {
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
if (second!= 0) {
result = first / second;
} else {
printf("Error: Division by zero\n");
return 1;
}
break;
default:
printf("Invalid operator\n");
return 1;
}
printf("Result: %.1lf\n", result);
return 0;
}