C Program to Make a Simple Calculator

Input: num1 = 10, num2 = 5, op = +
Output : res: 15.00
Explanation : Chosen operation is addition, so 10 + 5 = 15

Input: num1 = 12, num2 = 3, op = /
Output: res = 4.00
Explanation: The chosen operation is division, so 12 / 3 = 4

Simple Calculator Using switch Statement

The switch statement in C is a clean and efficient way to write a conditional code. Four switch-cases can be defined for four operations: addition, subtraction, multiplication and division. Then the value of input operator is tested. If it matches any case, statements inside that case are executed and result is returned. Otherwise, the default case will be executed.

Simple Calculator Program using switch Statement

Output

Enter an operator (+, -, *, /): +
Enter two operands: 10
5
Result: 15.00

Explanation: Here, the input operator is ‘+’. It is matched against the cases of the switch statement. The matching case is first case “case ‘+'”, so it will execute the statements inside the first case and break out of the switch. The result is then returned to the main.

If any case wouldn’t have matched, then -DBL_MAX(minimum value of double) would have been returned as a signal to the main function and result will not be printed.

Using if-else Statement

We can also create a simple calculator using if-else-if ladder . It allows us to execute the conditional code. The idea is to use a series of if-else statements to check the operator and perform the corresponding operation.

Program to Create a Simple Calculator Using if-else Statement

Output

Enter an operator (+, -, *, /): /
Enter two operands: 12
3
Result: 4.00

Explanation: Input operator is ‘/’. It is checked in each of the if and else if conditions. The matching condition is found at fourth else-if. The division calculation is performed, and result is returned.