How to make a calculator using switch case in C?

Share this Content

Hey friends.

Today we will make a fully functional calculator using switch case in C language and I will help you to understand every single line step by step.

Now let’s see what our calculator can do.

It’s a calculator that can perform arithmetic calculations such as Addition, Subtraction, Multiplication, Division, Modulus, Factorial and Power. Its starts with the display of the title “CALCULATOR” at the top and below that will be the list of operations it can perform. For every operation there is a unique symbol (set as per the operator). The user according to his/her choice can press the symbol through their keyboard and enter into their respective operations. Here, they will get another set of instructions along with an input field where they can type in the operands. To take exit from the program the user can press ‘Q’ or’q’.

Now, I’ve said that I’ll make this calculator using switch case statement. But before implementing it in the code we should know first about it.

What is the Switch Case statement?

A Switch Case statement is a type of selection statement that allows you to choose from several options based on the value of a particular expression. The expression is usually a variable but can be any valid expression.

The syntax of a Switch Case statement is as follows:

switch (expression)
{
case value1:

statement1;

break;

case value2:

statement2;

break;
default:

defaultStatement;

}

The expression is evaluated, and the resulting value is compared to the values in each case. The statement associated with that case is executed if there is a match, and if there is no match, the default statement is executed.

You can have multiple cases with the same statement. For example, if you want to execute the same statement for two different values of the expression, you can do this:

switch (expression)

{

case value1:

case value2:

statement;

break;

}

You can also have multiple statements associated with a single case. In this case, the statements must be enclosed in curly braces:

switch (expression)
{
case value:

statement1;

statement2;

break;
}

It is important to remember the break statement at the end of each case. Without the break statement, the code for the next case will be executed, even if the expression does not match the value for that case.

Here is a simple example of a Switch Case statement. In this example, we have a variable called the day that holds a value from 1 to 7, representing the days of the week. We use a Switch Case statement to print out the day’s name based on the value of the day variable.

Subscribe to Tech Break
int day = 3;

switch (day)

{

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;

default:

System.out.println("Invalid day");

}

In this example, the expression is the variable day. The value of the day is compared to the values in each case.

Calculator Using Switch Case:

Here is the code for the calculator. The code is written in C language. To understand every bit of the code, read the comments.

Code:

#include <stdio.h>
/* stdio.h - it is known to contain the input and output operations like "printf" or "scanf".
".h" extension means the header file. */

#include <math.h>

/*math.h - it is a header file in the standard library of the C programming language designed for basic mathematical operations.*/

#include <stdlib.h>

/* stdlib.h - is the header of the general purpose standard library 
of C programming language which includes functions involving memory allocation, process control, conversions and others. */

long double addition ();
void subtraction ();
long double multiplication ();
void division ();                               
void modulus ();
long double power ();
long long factorial ();
int **matrix_sum();
int **matrix_multiply();
double multiply();
double getNthRoot();
void calculator_operations ();

/* main () - It is the function from where the program starts getting executed. In this function “choice_operation” of char type is declared. Then the function calculator_operation () is called. Then, through scanf () user choice for the case label is accepted which is stored in “choice_operation” variable. Finally, the switch is executed. */
int main ()
{
    char choice_operation;
    calculator_operations ();       
    scanf ("%c", &choice_operation);
      //We are using switch statement here.
    /*It is a case control instruction that allows us to get a result from a number of choise 
    It's syntax is like-
    switch (expression)
    {
    case // constant-expression :
        //(code)
        break;
    
    default:
        break;
    } */
  
    switch(choice_operation)
        {
            case '+':; 
            long double add;
            add= addition();
            printf("Total: %Lf",add);
            break;

            case '-':; 
            long double first,second,third;
            subtraction(&first,&second,&third) ;
            printf("Subtraction of %Lf and %Lf is: %Lfnn",first,second,third);
            break;

            case '*':; 
            long double mul;
            mul= multiplication();
           	printf("Multiplication: %Lf",mul);
            break;

            case '/':;
            long double fir,sec,thi;
            division(&fir,&sec,&thi) ;
            printf("Division of %Lf and %Lf is: %Lfnn",fir,sec,thi);
            break;

            case '?':;
            int ff,tt,ss;
            modulus(&ff,&ss,&tt) ;
            printf("Modulus of %d and %d is: %dnn",ff,ss,tt);
            break;

            case '!':;
            long long fact=factorial ();
            printf ("Factorial of entered number is: %llin", fact);
            break;

            case '^':;
            long double p=power();
            printf("power %Lf",p);
            break;

            case 'D': calculator_operations ();
                      break;
                      
            case 'd': calculator_operations ();
                      break;
                      
            case 's':; 
            int x[100][100], y[100][100];
            int **a;
            int i,j,m,n;
            printf("Enter the number of rows and columns of matrixn"); 
            scanf("%d%d", &m, &n);
 
            printf("Enter the matrix1: n");
            for(i = 0; i < m; i++)
            {
            for(j = 0; j < n; j++)
            {
            	scanf("%d",&x[i][j]);
            }
            }
            printf("Enter the matrix2: n");
            for(i = 0; i < m; i++)
            {
            for(j = 0; j < n; j++)
            {
            	scanf("%d",&y[i][j]);
            } 
            }
            a = matrix_sum(x,y); 
            printf("The sum of the matrix is: n");
            for(i = 0; i < m; i++)
            {
            for(j = 0; j < n; j++)
            {
                printf("%d",a[i][j]);
                printf("t");
            }
            printf("n");
            }
            break;
            
            case 'm':;
            int e[100][100], f[100][100];
            int **b;
            int ii,jj,mm,nn;
            printf("Enter the number of rows and columns of matrixn"); 
            scanf("%d%d", &m, &n);
            printf("Enter the matrix1: n");
            for(ii = 0; ii < m; ii++)
            {
            for(jj = 0; jj < n; jj++)
            {
            	scanf("%d",&e[ii][jj]);
            }
            }
            printf("Enter the matrix2: n");
            for(ii = 0; ii < m; ii++)
            {
            for(jj = 0; jj < n; jj++)
            {
               scanf("%d",&f[ii][jj]);
            }
            }
            b = matrix_multiply(e,f); 
            printf("The multiplication of the matrix is: n");
            for(ii = 0; ii < m; ii++)
            {
            for(jj = 0; jj < n; jj++)
            {
                printf("%d",b[ii][jj]);
                printf("t");
            }
            printf("n");
            }
            break;
            
            case 'r':;
            int no, mo;
	        double result;
	        printf("Enter the rootn");
	        scanf("%d",&no);
	        printf("Enter the Numbern");
	        scanf("%d",&mo);
	        result=getNthRoot(no, mo); 
	        printf("The result is %lf",result);
            break;
            
            case 'Q': exit (0);
                      break;
                      
            case 'q': exit (0);
                      break;

            default:
               { 
                printf ("Please enter valid choicen");
                calculator_operations ();
               }
        }
}

/* calculator_operations () - In this function through printf () all the different type of operations are printed along with the symbol (case labels) which the user can press to enter the respective cases. */
void calculator_operations ()
{
    printf("___CALCULATOR__n");
    printf ("To Quit press 'Q' or 'q'n");
    printf ("To Display press 'D' or'd'n");
    printf ("Enter + symbol for Addition n");
    printf ("Enter - symbol for Subtraction n");
    printf ("Enter * symbol for Multiplication n");
    printf ("Enter / symbol for Division n");
    printf ("Enter? symbol for Modulusn");
    printf ("Enter ^ symbol for Power n");
    printf ("Enter! symbol for Factorial n");
    printf ("Enter s for Matrix Sum n");
    printf ("Enter m for Matrix Multiplication n");
    printf ("Enter r for Nth Root n");
}

/* addition () - variable “n”, “i” of int type is declared ,"total->0","number" of long double type is declared and a pointer variable "* ptr" is declared of long double type. Then, the user is asked to enter the number of operands they want to add and dynamically space is created .Using the for loop the operands are accepted one by one and again using the for loop the sum is calculated one by one of each element in the array and is stored in "total" .The result stored in “total” is returned. */
long double addition ()
{
    long double* ptr;
    int n, i;
    long double total=0, number;
    printf ("nEnter the number of elements you want to add:");
    scanf ("%d", &n);
    ptr = (long double*)malloc(n * sizeof(long double));
    if (ptr == NULL) 
    {
        printf("Memory not allocated.n");
        exit(0);
    }
    printf("Enter the numbers: n");
    for (i=0;i<n;i++) 
    {
        printf("Enter Number %d:",i+1);
        scanf("%Lf",&ptr[i]);
    }
   for (i=0; i<n; i++)
    {
        total=total+ptr[i];
    }
    return total;
}
  
/*the address of "a", "b", "c" is taken.Then the numbers are  
  accepted from the user and stored in the addresses, then the 
  subtraction is calculated and the result stored in the address of “c” */
  
void subtraction (long double* a,long double* b,long double* c)
{ 
    printf("Enter the two numbers:n");
    scanf("%Lf",&(*a));
    scanf("%Lf",&(*b));
    *c = *a - *b; 
}

/*multiplication () - variable “n”, “i” of int type is declared ,"mul->1","number" of long double type is declared and a pointer variable "* ptr" is declared of long double type. Then, the user is asked to enter the number of operands they want to multiply and dynamically space is created .Using the for loop the operands are accepted one by one and again using the for loop the multiplication is done one by one of each element in the array and is stored in "mul" .The result stored in “mull” is returned */

long double multiplication ()
{
    long double* ptr;
    int n, i;
    long double mul=1, number;
    printf ("nEnter the number of elements you want to multiply:n");
    scanf ("%d", &n);
    ptr = (long double*)malloc(n * sizeof(long double));
    if (ptr == NULL) 
    {
        printf("Memory not allocated.n");
        exit(0);
    }
    printf("Enter the numbers: n");
    for (i=0;i<n;i++) 
    {
        printf("Enter Number %d:",i+1);
        scanf("%Lf",&ptr[i]);
    }
   for (i=0; i<n; i++)
    {
        mul=mul*ptr[i];
    }
    return mul;
}
/* division () - the address of "fir", "sec", "thi" is taken.
Then the numbers are  accepted from the user and stored in the addresses,
then the division is calculated and the result is stored in the address of “thi” */
void division (long double* fir,long double* sec,long double* thi)
{ 
    printf("Enter the two numbers:n");
    scanf("%Lf",&(*fir));   
    scanf("%Lf",&(*sec));
    *thi = *fir / *sec; 
}
/*modulus () - the address of "ff", "ss", "tt" is taken.
Then the numbers are  accepted from the user and stored in the addresses,
then the modulus is calculated and the result is stored in the address of “tt”  */
void modulus (int* ff,int* ss,int* tt)
{ 
    printf("Enter the two numbers:n");
    scanf("%d",&(*ff));   
    scanf("%d",&(*ss));
    *tt = *ff % *ss; 
}
/* power () - variable “a”, “num”, “p” of long double type is declared.
Then, the user is asked for the two operands
(first the base which is stored in “a” and second the exponent which is stored in “num”). 
Then we run a for loop in which a is getting multiplied to itself as long as the loop runs.
Finally, the result is returned*/
long double power ()
{
    long double a, num, p=1;
    printf ("nEnter two numbers to find the power n");
    printf ("number: ");
    scanf ("%Lf", &a);
    printf ("power: ");
    scanf ("%Lf", &num);
    for(int i=0;i<num;i++)
    {
        p*=a;
    }
    return p;
}
/* factorial () - variable “i”, “num” of int type and “fact->1” of long long type is declared. Next the number whose factorial is to be done is accepted.
Then with a if statement it is checked whether it is a negative number or not and if it turns out to be a negative number the program terminates with a message.
Then using a for loop which runs from 1 to num the factorial is calculated and stored in “fact”. Finally, the result is returned. */
  
long long factorial ()
{
    int i, num;
    long long fact=1;
    printf ("Enter a number to find factorial:n");
    scanf ("%d", &num);
   if (num<0)
    {
        printf ("You need to enter a positive numbern");
        return 0;
    }
    else
    {
     for (i=1; i<=num; i++)
     fact=fact*i;
     return fact;
    }
}

/*int **matrix_sum() - "i","j" of type int is declared. "**matrix3" is an integer pointer to another pointer variable. size of "matrix3" is dynamically allocated. For loop is run from 1 to 100 in which size of row is allocated dynamically. Then the sum operation is done through loops and the result is returned*/
  
int **matrix_sum(int matrix1[][100], int matrix2[][100])
{
    int i, j;
    int **matrix3;
    matrix3 = malloc(sizeof(int*) * 100);
     
    for(i = 0; i <100; i++) 
    {
        matrix3[i] = malloc(sizeof(int*) * 100);
    }
 
    for(i = 0; i < 100; i++)
    {
        for(j = 0; j < 100; j++)
        {
            matrix3[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
    return matrix3;
}
/*int **matrix_multiply() - "i","j","c","d","k","sum->0" of type int is declared. "**multiply" is an integer pointer to another pointer variable. size of "multiply" is dynamically allocated. For loop is run from 1 to 100 in which size of row is allocated dynamically. Then the multiplication operation is done through loops and the result is returned*/
  
int **matrix_multiply(int matrix1[][100], int matrix2[][100])
{
    int i,j,c,d,k,sum=0;
    int **multiply;
    multiply = malloc(sizeof(int*) * 100);
     
    for(i = 0; i <100; i++) 
    {
        multiply[i] = malloc(sizeof(int*) * 100);
    }
    for (c = 0; c < 100; c++)
      {
        for (d = 0; d < 100; d++)
          {
             for (k = 0; k < 100; k++)
               {
                  sum = sum + matrix1[c][k]*matrix2[k][d];
               }
            multiply[c][d] = sum;
            sum = 0;
          }
      }
  return multiply;
}
/*double multiply() - Variable "ans->1.0" of double type is declared. This function finds out the power of the variable "number" to "n" using for loop and the result is stored in "ans"  which is then returned */
  
double multiply(double number, int n) 
{
    double ans = 1.0;
    for(int i = 1;i<=n;i++) 
    {
        ans = ans * number;
    }
    return ans; 
}
/*double getNthRoot() - Variable "low->1", "high->m" and "eps->1e-6" of double type is declared. Now a while loop first checks whether "high"-"low" is greater than "eps".Inside the while loop variable "mid" of double type  stores the average of "low" and "high". With a if statement it is checked whether "multiply(mid, n)" is less than "m" and if it is less than "m"   "low" stores "mid" else "high" stores "mid". The variable "high" is returned*/
  
double getNthRoot(int n, int m) 
{
    double low = 1;
    double high = m;
    double eps = 1e-6; 
    
    while((high - low) > eps) 
    {
        double mid = (low + high) / 2.0; 
        if(multiply(mid, n) < m) 
        {
            low = mid; 
        }
        else 
        {
            high = mid; 
        }
    }
    return high;
}

Ok, so We’ve written the code. Now it’s time to check our code.

Let’s see

Output:

After running the program the first thing we can see is-


___CALCULATOR__
To Quit press 'Q' or 'q'
To Display press 'D' or'd'
Enter + symbol for Addition
Enter - symbol for Subtraction
Enter * symbol for Multiplication
Enter / symbol for Division
Enter? symbol for Modulus
Enter ^ symbol for Power
Enter! symbol for Factorial
Enter s for Matrix Sum
Enter m for Matrix Multiplication
Enter r for Nth Root

This will show everytime you run the program as a guide.

Addition

+ Enter the number of elements you want to add:2 Enter the numbers: Enter Number 1:12.5 Enter Number 2:10 Total: 22.500000

Subtraction

- Enter the two numbers: 12 5.5 Subtraction of 12.000000 and 5.500000 is: 6.500000

Factorial

! Enter a number to find factorial: 2 Factorial of entered number is: 2

Not only this, our calculator can do much more complicated operations.

You can see how it works by seeing the video below.

Test video:

If you have any doubt, you can ask in the comment box.

Share this Content
Snehasish Konger
Snehasish Konger

Snehasish Konger is the founder of Scientyfic World. Besides that, he is doing blogging for the past 4 years and has written 400+ blogs on several platforms. He is also a front-end developer and a sketch artist.

Articles: 192

Newsletter Updates

Join our email-newsletter to get more insights

Leave a Reply

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