C Examples Calculator Switch Case
## C Program to Build a Simple Calculator Using Switch Case
In this tutorial, you will learn how to create a simple arithmetic calculator in C using the `switch...case` statement. This program takes an operator (`+`, `-`, `*`, `/`) and two operands from the user, performs the corresponding mathematical operation, and displays the result.
---
### Introduction to the `switch...case` Statement
The `switch` statement in C is a multi-way branch statement. It provides an elegant way to dispatch execution to different parts of code based on the value of an expression.
Using `switch...case` is highly efficient and readable when you need to compare a single variable (like our operator character) against multiple constant values, making it the perfect choice for building a command-based utility like a calculator.
---
### C Source Code
Below is the complete, ready-to-run C program. The program uses `double` data types to support both integer and floating-point calculations.
```c
#include
int main() {
char operator;
double firstNumber, secondNumber;
// Step 1: Ask the user to input the desired operator
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
// Step 2: Ask the user to input two operands
printf("Enter two numbers: ");
scanf("%lf %lf", &firstNumber, &secondNumber);
// Step 3: Perform the calculation based on the operator
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber + secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber - secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber * secondNumber);
break;
case '/':
// Check for division by zero
if (secondNumber != 0.0) {
printf("%.1lf / %.1lf = %.1lf\n", firstNumber, secondNumber, firstNumber / secondNumber);
} else {
printf("Error! Division by zero is not allowed.\n");
}
break;
// If the operator does not match any case constant (+, -, *, /)
default:
printf("Error! The operator is not correct.\n");
}
return 0;
}
```
---
### How the Code Works
1. **Variable Declaration**:
* `char operator;` stores the arithmetic operator entered by the user.
* `double firstNumber, secondNumber;` store the two numbers for the calculation. We use `double` to handle decimal values with high precision.
2. **User Input**:
* `scanf("%c", &operator);` reads the character input.
* `scanf("%lf %lf", &firstNumber, &secondNumber);` reads two floating-point numbers.
3. **The Switch Evaluation**:
* The program evaluates the value of the `operator` variable.
* It matches the character with the corresponding `case` label (`'+'`, `'-'`, `'*'`, `'/'`).
* The `break` statement at the end of each case prevents "fall-through" execution into the next case.
4. **Default Case**:
* If the user enters an operator other than the four specified, the `default` block executes, printing an error message.
---
### Example Output
#### Example 1: Multiplication
```text
Enter an operator (+, -, *, /): *
Enter two numbers: 4 5
4.0 * 5.0 = 20.0
```
#### Example 2: Division
```text
Enter an operator (+, -, *, /): /
Enter two numbers: 15.5 2
15.5 / 2.0 = 7.8
```
#### Example 3: Invalid Operator
```text
Enter an operator (+, -, *, /): %
Enter two numbers: 4 5
Error! The operator is not correct.
```
---
### Key Considerations & Best Practices
* **Format Specifiers**: We use `%lf` in `scanf` to read a `double` value, and `%.1lf` in `printf` to display the double value rounded to one decimal place.
* **Division by Zero**: In mathematics, dividing a number by zero is undefined. In production-grade code, always include a conditional check (`if (secondNumber != 0.0)`) inside the division case to prevent runtime errors or crashes.
* **Buffer Issues with `scanf`**: If you expand this program to run in a loop, be aware that `scanf("%c", &operator)` might read leftover newline characters (`\n`) from the input buffer. Adding a leading space in the format string like `scanf(" %c", &operator)` can help bypass whitespace issues.
YouTip