Calculator Using Switch Case

Calculator by Switch Case

We will write a C program to make a basic calculator by using switch cases for understanding the basic structure of programming. In this program , we can calculate numbers easily by using proper syntax and algorithms.

Calculator Using Switch Case

Working of Program :

In the program, we will require two or more numbers from the user to perform some basic operations for calculation.

Problem 1

Write a program to make a calculator to perform some basic operations using switch case.

  • If the operator is ‘+’, then print the addition operation on the given integer.
  • If the operator is ‘-’, then print the subtraction operation on the given integer.
  • If the operator is ‘*’, then print the multiplication operation on the given integer.
  • If the operator is ‘/’, then print the division operation on the given integer.

Code

Run
#include<stdio.h>
int main ()
{
  int num1, num2;
  float result;
  char ch;
  printf ("Enter first number = ");
  scanf ("%d", &num1);
  printf ("Enter second number = ");
  scanf ("%d", &num2);
  printf ("Choose operator to perform operations = ");
  scanf (" %c", &ch);
  result = 0;
  switch (ch)
    {
    case '+':
      result = num1 + num2;
      break;
    case '-':
      result = num1 - num2;
      break;
    case '*':
      result = num1 * num2;
      break;
    case '/':
      result = num1 / num2;
      break;
    default:
      printf ("Invalid operation\n");
    }
  printf ("Result: %d %c %d = %f\n", num1, ch, num2, result);
  return 0;
}

Output

Enter first number = 6
Enter second number = 7
Choose operator to perform operations = +
Result: 6 + 7 = 13.000000

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription