C Program To Make A Simple Calculator Using If Else
This article will guide you through creating a simple calculator program in C using if-else statements. You will learn how to accept user input for numbers and an arithmetic operator, then perform the calculation and display the result.
Problem Statement
Developing a basic calculator is a fundamental exercise in programming that helps solidify understanding of input/output operations, conditional logic, and arithmetic operations. The challenge is to correctly process two numbers and a chosen operation (addition, subtraction, multiplication, or division) to produce the accurate result.
Example
Here is what the calculator program's output will look like when run:
Enter an operator (+, -, *, /): +
Enter two operands: 10
5
Result: 10.0 + 5.0 = 15.0
Background & Knowledge Prerequisites
To follow this article effectively, a basic understanding of the following C programming concepts is beneficial:
- Variables: Declaring and using variables of different data types (e.g.,
doublefor numbers,charfor the operator). - Input/Output: Using
scanf()to read user input andprintf()to display output. - Arithmetic Operators: Familiarity with
+,-,*,/. - Conditional Statements: Understanding the
if-else if-elsestructure for decision-making.
No special libraries or complex setups are required beyond a standard C compiler (like GCC).
Use Cases or Case Studies
A simple calculator program, while basic, forms the foundation for many computational tasks:
- Educational Tool: It's an excellent project for beginners to grasp core programming logic.
- Quick Calculations: For everyday arithmetic in command-line environments.
- Embedded Systems: Basic arithmetic functions are often integrated into microcontrollers for simple data processing.
- Part of Larger Applications: Calculator logic can be a component within more complex applications, such as financial tools or engineering simulations.
Solution Approaches
This section details how to implement a simple calculator using the if-else if-else structure.
Simple Calculator using if-else
This approach involves reading the operator and two numbers from the user, then using a series of if-else if-else statements to check the operator and perform the corresponding arithmetic operation.
Code Example
// Simple Calculator
#include <stdio.h>
int main() {
char operator_char;
double num1, num2, result;
// Step 1: Prompt user for the operator
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator_char); // Note the space before %c to consume newline
// Step 2: Prompt user for two operands
printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
// Step 3: Use if-else if-else to perform calculation based on operator
if (operator_char == '+') {
result = num1 + num2;
printf("Result: %.1lf %c %.1lf = %.1lf\\n", num1, operator_char, num2, result);
} else if (operator_char == '-') {
result = num1 - num2;
printf("Result: %.1lf %c %.1lf = %.1lf\\n", num1, operator_char, num2, result);
} else if (operator_char == '*') {
result = num1 * num2;
printf("Result: %.1lf %c %.1lf = %.1lf\\n", num1, operator_char, num2, result);
} else if (operator_char == '/') {
// Handle division by zero
if (num2 != 0) {
result = num1 / num2;
printf("Result: %.1lf %c %.1lf = %.1lf\\n", num1, operator_char, num2, result);
} else {
printf("Error! Division by zero is not allowed.\\n");
}
} else {
printf("Error! Invalid operator entered.\\n");
}
return 0;
}
Sample Output
Enter an operator (+, -, *, /): *
Enter two operands: 12.5
2
Result: 12.5 * 2.0 = 25.0
Enter an operator (+, -, *, /): /
Enter two operands: 10
0
Error! Division by zero is not allowed.
Stepwise Explanation
- Declare Variables:
-
char operator_char;: Stores the arithmetic operator entered by the user. -
double num1, num2, result;: Store the two floating-point numbers (operands) and the calculated result.doubleis used to handle decimal values.
- Get Operator Input:
-
printf("Enter an operator (+, -, *, /): ");: Prompts the user to enter an operator. -
scanf(" %c", &operator_char);: Reads the character entered by the user. The space before%cis crucial; it tellsscanfto consume any whitespace characters (like the newline character left in the buffer from a previous input) before reading the actual character.
- Get Operand Input:
-
printf("Enter two operands: ");: Prompts the user for the numbers. -
scanf("%lf %lf", &num1, &num2);: Reads twodoublevalues from the user and stores them innum1andnum2.
- Perform Calculation with
if-else if-else:
- The program enters a series of
if-else if-elsestatements. - Each
iforelse ifcondition checks ifoperator_charmatches a specific operator (+,-,*,/). - If a match is found, the corresponding arithmetic operation is performed, and the
resultis calculated. - For division (
/), an additionalif (num2 != 0)check is included to prevent "division by zero" errors, which would crash the program. Ifnum2is zero, an error message is printed. - The final
elseblock catches any invalid operator input, informing the user. -
printf("Result: %.1lf %c %.1lf = %.1lf\n", num1, operator_char, num2, result);: This line displays the input numbers, the operator, and the calculated result, formatted to one decimal place (.1lf).
- Return 0: Indicates successful program execution.
Conclusion
Building a simple calculator using if-else statements is an effective way to learn conditional logic and basic input/output in C programming. This approach clearly demonstrates how to handle different user choices and provides a robust structure to prevent common errors like division by zero, all within a straightforward and understandable code block.
Summary
- A basic C calculator uses
scanf()for input andprintf()for output. - The
if-else if-elsestructure is key for selecting the correct arithmetic operation based on the user's operator choice. - Error handling for division by zero (
num2 != 0) is essential for program stability. - Using
doublefor numbers allows for decimal calculations. - The
%cformat specifier inscanf(with a leading space) helps consume leftover newline characters from previous inputs, ensuring correct character input.