Program 1
Develop a program to simulate a
Simple Calculator that performs
basic arithmetic operations including
addition,
subtraction,
multiplication,
and
division with proper error handling for division by zero.
Algorithm
- Initialize: Start the program
- Input Operator: Read operator (+, -, *, /) from user
- Input Numbers: Read two double numbers (a, b) from user
- Process Operation: Use switch case to perform selected operation
- Check Division: For division, verify b ≠ 0 to prevent error
- Calculate Result: Perform the arithmetic operation
- Output: Display the result or error message
- Terminate: Stop the program
Flowchart
START
→
Input op
→
Input a, b
→
Switch(op)
→
Calculate & Display
→
STOP
Code
#include <stdio.h>
int main() {
char op;
double a, b;
// Prompt user for operator
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &op);
// Prompt user for two numbers
printf("Enter two numbers: ");
scanf("%lf %lf", &a, &b);
// Perform calculation based on operator
switch(op) {
case '+':
printf("Result = %.2lf\n", a + b);
break;
case '-':
printf("Result = %.2lf\n", a - b);
break;
case '*':
printf("Result = %.2lf\n", a * b);
break;
case '/':
if(b != 0)
printf("Result = %.2lf\n", a / b);
else
printf("Error! Division by zero.\n");
break;
default:
printf("Invalid operator!\n");
}
return 0;
}
Output
// Output 1 - Addition
Enter an operator (+, -, *, /): +
Enter two numbers: 15.5 10.3
Result = 25.80
// Output 2 - Multiplication
Enter an operator (+, -, *, /): *
Enter two numbers: 7.5 4.0
Result = 30.00
// Output 3 - Division
Enter an operator (+, -, *, /): /
Enter two numbers: 20.0 4.0
Result = 5.00
// Output 4 - Division by Zero Error
Enter an operator (+, -, *, /): /
Enter two numbers: 10.0 0.0
Error! Division by zero.
// Output 5 - Invalid Operator
Enter an operator (+, -, *, /): %
Enter two numbers: 8.0 3.0
Invalid operator!
Replay !
Share Your Thoughts