Creating a simple calculator program in C using if-else
statements is a great way to practice your programming skills. Below is a step-by-step guide along with the complete code for a basic calculator that can perform addition, subtraction, multiplication, and division.
Step-by-Step Guide
- Include Necessary Headers: Start by including the standard input-output header file.
- Declare Variables: You'll need variables to store the two numbers, the operator, and the result.
- Get User Input: Prompt the user to enter two numbers and an operator.
- Use if-else Statements: Based on the operator entered, use
if-else
statements to perform the corresponding arithmetic operation. - Display the Result: Print the result of the operation.
- Handle Division by Zero: Ensure that the program checks for division by zero to avoid errors.
Complete Code
Explanation of the Code
Input Handling:
- The program prompts the user to enter two numbers and an operator.
- The
scanf
function is used to read the input values.
Calculation Logic:
- The program checks the operator using
if-else
statements. - Depending on the operator, it performs the corresponding arithmetic operation.
- For division, it checks if the second number is zero to prevent division by zero.
- The program checks the operator using
Output:
- The result of the operation is printed to the console.
- If the operator is invalid, an error message is displayed.
How to Compile and Run
- Save the code in a file named
calculator.c
. - Open a terminal and navigate to the directory where the file is saved.
- Compile the program using the following command: