C Program to Create a Simple Calculator

In this program, we will learn to create a simple calculate in c programming using the switch case.

To create this program, you should have the Knowledge of the following C programming topics:

  • C 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 Case

For this C calculator program example, we used the Switch case to check which operand is inserted by the user. Next, based on the Operand result will display.

#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;
}

Recommended:

Leave a Comment

Your email address will not be published. Required fields are marked *