Calculator Program in C

A calculator is a device used to perform mathematical operations on numbers. Simple calculators can only perform the basic mathematical operations of addition, subtraction, multiplication, and division. In this article, we will explain a simple calculator program in C with an example.

Problem Solution

1. Declare the variables.
2. Get the two numbers from the user.
3. Get the operator from the user.
4. Calculate the result and store it in the variable ‘result’.
5. Display the result to the user.
6. Exit the Program.

Let’s discuss different ways to create a calculator program in C.

Method 1: Simple Calculator Program in C Using Switch Case

This C program constructs a simple calculator using a switch case statement.

Program/Source Code

Here is the source code of the C program that simulates a simple calculator using a switch case statement. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C program to simulate a simple calculator to perform arithmetic
 * operations like addition, subtraction, multiplication and division
 */
#include <stdio.h>
 
void main()
{
    char operator;
    float num1, num2, result;
 
    printf("Simulation of a Simple Calculator\n");
    printf("*********************************\n");
    printf("Enter two numbers \n");
    scanf("%f %f", &num1, &num2);
    fflush(stdin);
    printf("Enter the operator [+,-,*,/] \n");
    scanf("%s", &operator);
    switch(operator)
    {
        case '+': result = num1 + num2; // add two numbers
            break;
        case '-': result = num1 - num2; // subtract two numbers
            break;
        case '*': result = num1 * num2; // multiply two numbers
            break;
        case '/': result = num1 / num2; // divide two numbers
            break;
        default : printf("Error in operation");
            break;
    }
    printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2, result);
}
Program Explanation

In this C program, we read three float values and an operator symbol using the variables num1, num2, result and operator.

advertisement
advertisement

Switch case statement is used to perform arithmetic operations like addition, subtraction, multiplication and division in each case. The user enters the operator they want to use. If the operator does not match any case in the switch statement, the default statement is executed and the message ‘Error in operation’ is printed.

Examples:

  • Consider, the two numbers entered by user are 2 and 3, and the operator entered by the user is ‘+’. We enter the switch case and find that the operator + matches with the first case, so we will enter the first case i.e. case ‘+’ and compute the result (result = 2 + 3 = 5). Because result is a float variable, the output will be 5.00.
  • Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
  • Consider, the two numbers entered by user are 65000 and 4700, and the operator entered by the user is ‘’. We enter the switch case and find that the operator matches with the second case, so we will enter the second case i.e. case ‘-‘ and compute the result (result = 65000 – 4700 = 60300). Since, result is a float variable therefore, output printed will be 60300.00.

Time Complexity: O(1)
The above calculator program has a time complexity of O(1) as there are no loops and each condition is executed only once.

Space Complexity: O(1)
In the above program, space complexity is O(1) as no extra variable has been taken to store the values in the memory. All the variables initialized takes a constant O(1) space.

Runtime Test Cases

Test Case 1: In this case, we are simulating an addition operation with a simple calculator.

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
2 3
Enter the operator [+,-,*,/]
+
 
2.00 +  3.00 =  5.00

Test Case 2: In this case, we are simulating an multiplication operation with a simple calculator.

advertisement
 
Simulation of a Simple Calculator
*********************************
Enter two numbers
50 40
Enter the operator [+,-,*,/]
*
 
50.00 * 40.00 = 2000.00

Test Case 3: In this case, we are performing Division operation using simple calculator.

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
500 17
Enter the operator [+,-,*,/]
/
 
500.00 / 17.00 = 29.41

Test Case 4: In this case, we are performing Subtraction operation using simple calculator.

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
65000 4700
Enter the operator [+,-,*,/]
-
 
65000.00 - 4700.00 = 60300.00

advertisement
Method 2: Calculator Program in C using if-else

In this C Program, we are going to construct a simple calculator using if-else condition.

Program/Source Code

Here is the source code of the C program that simulates a simple calculator using the if-else condition. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C program to simulate a simple calculator to perform arithmetic
 * operations like addition, subtraction, multiplication and division
 */
 
#include <stdio.h>
 
void main()
{
    char operator;
    float num1, num2, result;
 
    printf("Simulation of a Simple Calculator\n");
    printf("*********************************\n");
    printf("Enter two numbers \n");
    scanf("%f %f", &num1, &num2);
    printf("Enter the operator [+,-,*,/] \n");
    scanf("%s", &operator);
    if(operator == '+')
        result = num1 + num2;
    else if(operator == '-')
        result = num1 - num2;
    else if(operator == '*')
        result = num1 * num2;
    else if(operator == '/')
        result = num1 / num2;
    else
        printf("Error in operation");
    printf("\n%5.2f %c %5.2f = %5.2f\n", num1, operator, num2, result);
}
Program Explanation

In this C program, we read three float values and an operator symbol using the variables num1, num2, result and operator.

An if-else statement is used to perform arithmetic operations like addition, subtraction, multiplication, and division depending on the operator entered by the user. The user enters the operator they want to use. If the operator does not match any condition in the if-else statement, the else statement is executed and the message “Error in operation” is printed.

Examples:

  • Consider, the two numbers entered by user are 50 and 40, and the operator entered by the user is ‘*’. Now, in the if-else condition we will check the condition that matches operator==’*’. Now, in that condition multiplication will be performed over the two numbers and the result (50*40 = 2000) will be stored in the result variable. Finally, the result will be printed as 2000.00.
  • Consider, the two numbers entered by user are 400 and 16, and the operator entered by the user is ‘/’. Now, in the if-else condition we will check the condition that matches operator==’/’. Now, in that condition multiplication will be performed over the two numbers and the result (400/16 = 25) will be stored in the result variable. Finally, the result will be printed as 25.00.

Time Complexity: O(1)
The above calculator program has a time complexity of O(1) because there are no loops and each condition is executed only once.

Space Complexity: O(1)
The program has a space complexity of O(1) because no additional variables are used to store the values in memory. All of the variables initialized require a constant amount of space (O(1)).

Runtime Test Cases

Test Case 1: Addition

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
3 5
Enter the operator [+,-,*,/]
+
 
3.00 + 5.00 =  8.00

Test Case 2: Multiplication

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
40 50
Enter the operator [+,-,*,/]
*
 
40.00 * 50.00 = 2000.00

Test Case 3: Division

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
400 16
Enter the operator [+,-,*,/]
/
 
400.00 / 16.00 = 25.00

Test Case 4: Subtraction

 
Simulation of a Simple Calculator
*********************************
Enter two numbers
6500 4700
Enter the operator [+,-,*,/]
-
 
5500.00 - 4100.00 = 1400.00

Method 3: Calculator Program in C using do-while and Switch Case

In this method, we are going to construct a simple calculator using do-while loop and Switch Case which will allow users to repeatedly perform calculation until they want to exit.

Program/Source Code

Here is the source code for a C program that simulates a simple calculator using a do-while loop and switch case. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 * C program to simulate a simple calculator to perform arithmetic
 * operations like addition, subtraction, multiplication, division, remainder etc.
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
void main()
{
    float num1, num2, result;  // used for all other operations except remainder
    int ch,n1,n2,res;  //used for remainder operation
    do{
        printf("\nSimulation of a Simple Calculator\n");
        printf("*********************************\n");
        printf("Select a number to perform operation on Calculator");
        printf("\n1->Addition\t 2->Subtraction\t 3->Multiplication\t 4->Division\t 
               5->Remainder\t 6- >Square\t 7->Square Root 8->Exit\n");
        scanf("%d",&ch);
 
        switch(ch)
        {
            // Add two numbers
            case 1:
                printf("Enter two numbers \n");
                scanf("%f %f", &num1, &num2);
                result = num1 + num2;
                printf("\n%.2f + %.2f = %.2f\n",num1,num2,result);
                break;
 
            // Subtract two numbers
            case 2:
                printf("Enter two numbers \n");
                scanf("%f %f", &num1, &num2);
                result = num1 - num2;
                printf("\n%.2f - %.2f = %.2f\n",num1,num2,result);
                break;
 
            // Multiplication of two numbers
            case 3:
                printf("Enter two numbers \n");
                scanf("%f %f", &num1, &num2);
                result = num1 * num2;
                printf("\n%.2f * %.2f = %.2f\n",num1,num2,result);
                break;
 
            // Division of two numbers
            case 4:
                printf("Enter two numbers \n");
                scanf("%f %f", &num1, &num2);
                result = num1 / num2;
                printf("\n%.2f / %.2f = %.2f\n",num1,num2,result);
                break;
 
            // Remainder of two numbers
            case 5:
                printf("Enter two numbers \n");
                scanf("%d %d", &n1, &n2);
                res = n1 % n2;
                printf("Remainder of two numbers = %d\n",res);
                break;
 
            // Square of number
            case 6:
                printf("Enter the number \n");
                scanf("%f", &num2);
                result = num2 * num2;
                printf("Square of %.2f = %.2f\n",num2,result);
                break;
 
            // Square root of a number
            case 7:
                printf("Enter the number \n");
                scanf("%f", &num1);
                result = sqrt(num1);
                printf("Square Root of %.2f = %.2f\n",num1,result);
                break;
 
            case 8:
                printf ("Execution Terminated");
                exit(0);
                break;
 
            default:
                printf("Error in Operation");
                break;
        }
    }while(ch!=8);
}
Program Explanation

In this C program, we use do-while loop and switch case. The do-while loop runs until the user give the input as 8(exit) while choosing operations that needs to be performed.

Switch case statement is used to perform arithmetic operations like addition, subtraction, multiplication, division etc. in each case. The user needs to enter the values on which they need to perform the operation in each specific switch case statement. If the user enters any other number except 1-8 while choosing the operation, then the default statement will be executed and an error message will be prompted “Error in operation”.

Examples:
In this calculator program, 1st the users need to choose the number associated with the operator on which they need to perform the calculation. Then they need to enter the number for calculation.

  • Suppose the operator chosen by user is ‘7 i.e., square root’. Now, in the switch case we will enter the case 7 where the user needs to enter a number to calculate square root. Suppose the number chosen by user is 49, so square root of 49 will be calculated and the result = 7 will be printed as output.
  • Suppose the operator chosen by user is ‘6 i.e., square’. Now, in the switch case we will enter the case 6 where the user needs to enter a number to calculate square of a number. Suppose the number chosen by user is 5, so square root of 5 will be calculated and the result = 25 will be printed as output.

Time Complexity: O(n)
The above calculator program has a time complexity of O(n) as there is a do while loop and each condition is executed only once, where n is the number of times user enters the choice before exiting the condition.

Space Complexity: O(1)
In the above program, space complexity is O(1) as no extra variable has been taken to store the values in the memory. All the variables initialized takes a constant O(1) space.

Runtime Test Cases
 
Simulation of a Simple Calculator
*********************************
Select a number to perform operation on Calculator
1->Addition     2->Subtraction     3->Multiplication     4->Division      5->Remainder
6->Square     7->Square Root     8->Exit
1
Enter two numbers
2 3
2.00 + 3.00 = 5.00
 
Simulation of a Simple Calculator
*********************************
Select a number to perform operation on Calculator
1->Addition     2->Subtraction     3->Multiplication     4->Division      5->Remainder
6->Square     7->Square Root     8->Exit
5
Enter two numbers
10 8
Remainder of two numbers = 2
 
Simulation of a Simple Calculator
*********************************
Select a number to perform operation on Calculator
1->Addition     2->Subtraction     3->Multiplication     4->Division      5->Remainder
6->Square     7->Square Root     8->Exit
6
Enter the number
5
Square of 5.00 = 25.00
 
Simulation of a Simple Calculator
*********************************
Select a number to perform operation on Calculator
1->Addition     2->Subtraction     3->Multiplication     4->Division      5->Remainder
6->Square     7->Square Root     8->Exit
7
Enter the number
49
Square Root of 49.00 = 7.00
 
Simulation of a Simple Calculator
*********************************
Select a number to perform operation on Calculator
1->Addition     2->Subtraction     3->Multiplication     4->Division      5->Remainder
6->Square     7->Square Root     8->Exit
8
Execution Terminated

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.