๐Ÿ”€โšกBeginner

Make a Simple Calculator

Calculator using switch-case

This program creates a simple calculator that performs basic arithmetic operations using the switch statement. It demonstrates how to handle multiple choices efficiently.

C Program: Simple Calculator

calculator.c
C
1#include <stdio.h>
2
3int main() {
4 char operator;
5 double num1, num2, result;
6
7 printf("Enter operator (+, -, *, /): ");
8 scanf(" %c", &operator); // Note the space before %c
9
10 printf("Enter two numbers: ");
11 scanf("%lf %lf", &num1, &num2);
12
13 switch (operator) {
14 case '+':
15 result = num1 + num2;
16 printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
17 break;
18
19 case '-':
20 result = num1 - num2;
21 printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
22 break;
23
24 case '*':
25 result = num1 * num2;
26 printf("%.2lf ร— %.2lf = %.2lf\n", num1, num2, result);
27 break;
28
29 case '/':
30 if (num2 != 0) {
31 result = num1 / num2;
32 printf("%.2lf รท %.2lf = %.2lf\n", num1, num2, result);
33 } else {
34 printf("Error: Division by zero!\n");
35 }
36 break;
37
38 default:
39 printf("Invalid operator!\n");
40 }
41
42 return 0;
43}
Output

Enter operator (+, -, *, /): *

Enter two numbers: 12.5 4

12.50 ร— 4.00 = 50.00

Understanding Switch Statement

switch (expression)

Evaluates the expression once

case value:

Compares with each case value

break;

Exits the switch block (IMPORTANT!)

default:

Executes if no case matches

โš ๏ธ Do Not Forget break!

Without break, execution "falls through" to the next case:

main.c
C
1case '+':
2 result = num1 + num2;
3 // Missing break - will execute next case too!
4case '-':
5 result = num1 - num2; // This runs even for '+'!

๐Ÿ“ Key Takeaways

โœ“switch for multiple fixed choices
โœ“Always use break after each case
โœ“default handles invalid input
โœ“Check division by zero!