C Example for Beginners: C Program to Make a Simple Calculator Using switch…case

(C programming Example for Beginners)

C Program to Make a Simple Calculator Using switch…case

In this example, you will learn to create a simple calculator in C programming using the switch statement.


This program takes an arithmetic operator +, -, *, / and two operands from the user. Then, it performs the calculation on the two operands depending upon the operator entered by the user.


Simple Calculator using switch Statement


#include <stdio.h>
int main(){
    char operator;
    double first, second;
    printf("Enter an operator (+, -, *,): ");
    scanf("%c", &operator);
    printf("Enter two operands: ");
    scanf("%lf %lf", &first, &second);

    switch (operator) {
    case '+':
        printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
        break;
    case '-':
        printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
        break;
    case '*':
        printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
        break;
    case '/':
        printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
        break;
        // operator doesn't match any case constant
    default:
        printf("Error! operator is not correct");
    }

    return 0;
}

Output

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8

The * operator entered by the user is stored in operator. And, the two operands, 1.5 and 4.5 are stored in first and second respectively.

Since the operator * matches case '*':, the control of the program jumps to

printf("%.1lf * %.1lf = %.1lf", first, second, first * second);

This statement calculates the product and displays it on the screen.

Finally, the break; statement ends the switch statement.

 

 

C Example for Beginners: C Program to Make a Simple Calculator Using switch…case

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.