C++ program to create calculator

In this blog, we will create a program to make a calculator in the C++ programming language.

What is Calculator?

A calculator is a device that performs various functions like addition, subtraction, multiplication, division, and many more.

Algorithm to write the respective code

The program below creates a simple calculator in C++ programming that performs four basic math operations such as addition, subtraction, multiplication, and division depending on the user’s choice.

To perform a calculator task, first, accept a choice and then any two numbers (unless there is an exit choice). Then use the switch case to identify the option and do the required things as shown in the program below:

The question is, write a calculator program in C++. Here is his response:

C++ code for the respective program

#include<iostream>
using namespace std;
int main()
{
    float numOne, numTwo, res;
    int choice;
    do
    {
        cout<<"1. Addition\n";
        cout<<"2. Subtraction\n";
        cout<<"3. Multiplication\n";
        cout<<"4. Division\n";
        cout<<"5. Exit\n\n";
        cout<<"Enter Your Choice(1-5): ";
        cin>>choice;
        if(choice>=1 && choice<=4)
        {
            cout<<"\nEnter any two Numbers: ";
            cin>>numOne>>numTwo;
        }
        switch(choice)
        {
            case 1:
                res = numOne+numTwo;
                cout<<"\nResult = "<<res;
                break;
            case 2:
                res = numOne-numTwo;
                cout<<"\nResult = "<<res;
                break;
            case 3:
                res = numOne*numTwo;
                cout<<"\nResult = "<<res;
                break;
            case 4:
                res = numOne/numTwo;
                cout<<"\nResult = "<<res;
                break;
            case 5:
                return 0;
            default:
                cout<<"\nWrong Choice!";
                break;
        }
        cout<<"\n------------------------\n";
    }while(choice!=5);
    cout<<endl;
    return 0;
}

Output of the above code

*For division

*For addition

*For subtraction

*For multiplication

*And to perform no function press 5*

Explanation of the code

Enter your choice say 3 if you want to do multiplication. After entering 3 as an option, press ENTER.
Now enter any two numbers say 3,4 and 3 as input. Then press ENTER to print the multiplication result
As you can see, the program will ask for the option to perform the operation again until the user enters 5 as the option to exit the calculator.