Write a C Program to Implement Calculator using switch case. It should perform basic operations such as add, subtract, product and divide.

This is the common program you will encounter while learning switch-case statements in C programming language.

Since, it is explicitly mentioned in the program definition that we have to use the switch-case statement. Here, you have to accept 3 inputs from the user, two numbers and one operation symbol (+, -, *, /).

Tutorial 📺

Watch tutorial and learn how to solve this problem. 😉

Steps 🪜

To implement calculator using switch case

  1. First of all, display a list operations to the user and accept two numbers as well as the operation symbol such as +, – etc.
  2. Create a case for each operation symbol and the default case, to handle the situation if the user enters invalid operation symbol.
  3. For operation symbol ‘+’, display the result of adding two numbers and add break statement. Follow the same procedure for remaining operation symbols displaying result along with break statement.
  4. Finally, display a message in default case, “Invalid Operation Symbol Entered“.

Code 💻

// Write a C program to implement Calculator using switch case.

#include<stdio.h>
#include<conio.h>

void main()
{
  float n1 = 0, n2 = 0;
  char oper;
  clrscr();
  printf("\t=== Calculator ===\n");
  printf("\n+ for Addition");
  printf("\n- for Subtraction");
  printf("\n* for Multiplication");
  printf("\n/ for Division");
  printf("\nPlease enter the operation (symbol): ");
  scanf("%c", &oper);
  printf("\nPlease enter the n1: ");
  scanf("%f", &n1);
  printf("\nPlease enter the n2: ");
  scanf("%f", &n2);
  // Perform Operation based on entered values using Switch-case
  switch(oper)
  {
    case '+': 
      printf("\nAddition: %0.2f + %0.2f = %0.2f", n1, n2, n1 + n2); 
      break;
    case '-': 
      printf("\nSubtraction: %0.2f - %0.2f = %0.2f", n1, n2, n1 - n2); 
      break;
    case '*': 
      printf("\nMultiplication: %0.2f * %0.2f = %0.2f", n1, n2, n1 * n2); 
      break;
    case '/': 
      printf("\nDivision: %0.2f / %0.2f = %0.2f", n1, n2, n1 / n2); 
      break;
    default: printf("\nInvalid Operation Symbol Entered.");
  }
  getch();
}

Example 😍

Let’s assume, the user enters ‘-‘ as operation symbol and two numbers as 15.5 and 20.

Next, switch statement will evaluate value stored in oper variable i.e. ‘-‘ and will execute the statements of matching case. There is a matching case, so it will display the following result:

Subtraction: 15.5 - 20.0 = -4.5

Let’s take another example where the user enters ‘=’ as operation symbol and two numbers as 40 and 30.

Again, switch statement will evaluate the oper variable. Since, there is no matching case, so it will execute the default case and display the message as:

Invalid Operation Symbol Entered.

This is how we write a C program to implement calculator using switch case.
For more C programs, click here.

Categorized in: