OverIQ.com

C Program to simulate a simple calculator using switch statement

Last updated on July 27, 2020


The following is a C Program to simulate a simple calculator using the switch statement:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/***************************************************************
 Program to simulate a simple calculator using switch statement
 * 
 * Enter an expression: 100+50
 * Result: 150
 * 
 * Enter an expression: 21*21
 * Result: 441
 **************************************************************/
 
#include<stdio.h> // include stdio.h library

int main(void)
{       
    int a, b, result;
    char op; // to store the operator
    
    printf("Enter an expression: ");
    scanf("%d%c%d", &a, &op, &b);

    switch(op)
    {
        case '+':
            result = a + b;
            break;
        case '-':
            result = a - b;
            break;
        case '*':
            result = a * b;
            break;
        case '/':
            result = a / b;
            break;              
    }
    
    printf("Result = %d", result);
    
    return 0; // return 0 to operating system
}

Expected Output:

1st run:

1
2
Enter an expression: 10+40
Result = 50

2nd run:

1
2
Enter an expression: 65*65
Result = 4225

Recommended Reading: