- 1C Hello World Program
- 2C Program to Print Your Own Name
- 3C Program to Print an Integer Entered by the User
- 4C Program to Add Two Numbers
- 5C Program to Multiply Two Floating‑Point Numbers
- 6C Program to Print the ASCII Value of a Character
- 7C Program to Swap Two Numbers
- 8C Program to Calculate Fahrenheit to Celsius
- 9C Program to Find the Size of int, float, double and char
- 10C Program - Add Two Complex Numbers
- 11C Program - Find Simple Interest
- 12C Program - Find Compound Interest
- 13C Program - Area And Perimeter Of Rectangle
- 14C Program - Check Whether a Number is Positive, Negative, or Zero
- 15C Program - Check Whether Number is Even or Odd
- 16C Program - Check Whether a Character is Vowel or Consonant
- 17C Program - Find Largest Number Among Three Numbers
- 18C Program - Calculate Sum of Natural Numbers
- 19C Program - Print Alphabets From A to Z Using Loop
- 20C Program - Make a Simple Calculator
- 21C Program - Generate Multiplication Table
- 22C Program - Reverse a Number
- 23C Program - Check whether the input number is a Neon Number
- 24C Program - Find All Factors of a Natural Number
C Program to Make a Simple Calculator - Switch‑Case Operations
Simple Calculator Using Switch Statement
#include <stdio.h>
int main() {
double num1, num2;
char op;
printf("Enter an operator (+, -, *, /, %c): ", '%');
scanf(" %c", &op);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch (op) {
case '+':
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
break;
case '-':
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
break;
case '/':
if (num2 == 0) {
printf("Error! Division by zero is not allowed.\n");
} else {
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
}
break;
case '%':
// Modulus works on integers, cast the numbers
printf("%d %% %d = %d\n", (int)num1, (int)num2, (int)num1 % (int)num2);
break;
default:
printf("Error! Operator not supported.\n");
}
return 0;
}
Enter an operator (+, -, *, /, %): *
Enter two numbers: 7.5 4
7.5 * 4 = 30.00
This calculator asks the user to choose an operator and then enter two numbers. A switch statement performs the selected arithmetic operation. Note how division by zero is checked before attempting the calculation. Modulus requires integer operands, so casting is used when computing %.
⬅ Previous TopicC Program - Print Alphabets From A to Z Using Loop
Next Topic ⮕C Program - Generate Multiplication Table
Next Topic ⮕C Program - Generate Multiplication Table
Comments
Loading comments...