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
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
// Get user input
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Note the space before %c to consume any leftover whitespace
printf("Enter second number: ");
scanf("%f", &num2);
// Perform calculation based on the operator
if (operator == '+') {
result = num1 + num2;
printf("%.2f + %.2f = %.2f\n", num1, num2, result);
} else if (operator == '-') {
result = num1 - num2;
printf("%.2f - %.2f = %.2f\n", num1, num2, result);
} else if (operator == '*') {
result = num1 * num2;
printf("%.2f * %.2f = %.2f\n", num1, num2, result);
} else if (operator == '/') {
if (num2 != 0) {
result = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
} else {
printf("Error! Division by zero.\n");
}
} else {
printf("Invalid operator! Please use +, -, *, or /.\n");
}
return 0;
}
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:
gcc calculator.c -o calculator
Run the program:
./calculator
No comments:
Post a Comment
If you have any doubts, please let me know