Q. C program to make a simple calculator using switch case.


Here you will find an algorithm and program in C programming language to make a simple calculator. First let us understand what is calculator?

Explanation : A calculator is used to make mathematical calculations. In this program we will create a simple calculator that can perform an arithmetic operation (+, -, *, /).

Calculator Program Algorithm


START
Step 1 : Initialise the two numbers.
Step 2 : Ask the user to enter an option by giving six options.
Step 3 : After getting the option from the user write if conditions for every operation based on the option.
Step 4 : Perform the respective operation.
Step 5 : Print the result.
STOP

C Program to Make a Simple Calculator

#include <stdio.h>
int main() {
  char ch;
  double num1, num2;
  printf("Enter an operator (+, -, *, /): ");
  scanf("%c", &ch);
  printf("Enter two operands: ");
  scanf("%lf %lf", &num1, &num2);
  switch (ch) {
  case '+':
    printf("%.1lf + %.1lf = %.1lf", num1, num2, num1 + num2);
    break;
  case '-':
    printf("%.1lf - %.1lf = %.1lf", num1, num2, num1 - num2);
    break;
  case '*':
    printf("%.1lf * %.1lf = %.1lf", num1, num2, num1 * num2);
    break;
  case '/':
    printf("%.1lf / %.1lf = %.1lf", num1, num2, num1 / num2);
    break;

  // operator doesn't match any case constant
  default:
    printf("Error! operator is not correct");
  }
  return 0;
}

Output

Enter an operator (+, -, *, /): *
Enter two operands: 8 6
8.0 * 6.0 = 48.0