×

Calculator Program in C++

Calculator Program in C++

A calculator program is a simple instructional and case action program that does numerical calculations. We can carry out simple to complex operations depending on the type of our requirement. There are hundreds of ways to make a calculator in C++ ranging from simple to complex instructions.

Let us look at some of the main ways to make a calculator in C++

Example 1:

 #include<bits/stdc++.h>
 using namespace std;
 int main()
 {
     char operation;
     float number1, number2;
     cout<<"Enter the operation you want to perform: ";
     cin >> operation;
     cout<<"Enter two numbers: ";
     cin >> number1 >> number2;
 switch (operation) {
         case '+':
             cout << number1 + number2;
             break;
         case '-':
             cout << number1 - number2;
             break;
         case '*':
             cout << number1 * number2;
             break;
         case '/':
             cout << number1 / number2;
             break;
         default:
             cout << "Invalid Input";
             break;
     } 
     return 0; 
 }  

Output:

Calculator Program

Explanation:

First, we have defined a variable name operation and seek the user to enter what kind of operation he/she wants to perform. The next task is taking two numbers, which is defined in the code as number1 and number2 respectively. The next task is to define switch cases.

A switch case shifts the operation based on the entry by the user and performs the necessary action. The control flow of the switch case can be easily understood from the code itself, though below algorithmic logic and flowchart explains it leaving no doubts.

Calculator Program

Algorithm:

START

  1. Print "Enter the operation you want to perform"
  • Enter your choice
  • Enter two operands
  • If the user enters + or - or * or / then follow the instructions or     else return default i.e invalid option.
  • Switch(operator)

    A.  case +:

                   i.                 Print ‘Addition’.

                    ii.                Print result of addition.

                   iii.               break

B.        case -:

                   i.                 Print ‘Subtraction’.

                   ii.                Print result of subtraction.

            break

C.        case *:

                   i.                 Print ‘Multiplication’.

                   ii.                Print result of multiplication.

                   iii.               break

    D.  case /:

                   i.                 Print ‘Division’.

                   ii.                Print result of division.

                   iii.               break

          E.      default:

                   i.        Print ‘Invalid Option’.

STOP

Let us look at another example to perform all the operations together so that users don’t have to seek each and every-time for it.

Example 2:

 #include<bits/stdc++.h>
 using namespace std;
 template <class T>
 class Calculator
 {
 private:
         T num1, num2;
 public:
         Calculator(T n1, T n2)
         {
                 num1 = n1;
                 num2 = n2;
         }
         void displayResult()
         {
                 cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
                 cout << "Addition is: " << add() << endl;
                 cout << "Subtraction is: " << subtract() << endl;
                 cout << "Product is: " << multiply() << endl;
                 cout << "Division is: " << divide() << endl;
         }
         T add() { return num1 + num2; }
         T subtract() { return num1 - num2; }
         T multiply() { return num1 * num2; }
         T divide() { return num1 / num2; }
 };
 int main()
 {
         Calculator<int> intCalc(2, 1);
         Calculator<float> floatCalc(2.4, 1.2);
         cout << "Int results:" << endl;
         intCalc.displayResult();
         cout << endl << "Float results:" << endl;
         floatCalc.displayResult();
         return 0;
 } 

Output:

Calculator Program

Note: The above code is for integer and float data-types.

Explanation:

In the above code, the Object-Oriented Programming methodology is used just to showcase the standard procedure of a calculator. It is quite applicable to using the Standard Template Library(STL) in C++. The class Calculator is defined using the template class T to reduce the complexity of writing repeating terms more often. Using template class increases the accessibility of the program. Therefore, intCalc() and floatCalc() are the two functions defined to calculate values for integers and float as well. Another function displayResult() displays the result on the screen after the code execution.

Template class syntax can be understood by the following pseudo code:

 template <class type> return_type func_name(parameter list)
 {
 // body of function
 } 

Also, the add(), subtract(), divide(), multiply() are the functions which have both integer and float return type. These functions have two arguments num1 and num2 which are already initialized in the driver code as (2,1) for intCalc() function and (2.4, 1.2) for floatCalc() function.

The above code returns 0 as exit code since it is normal termination.

Summary

There are various ways to code a simple calculator program in C++. The Standard Template Library (STL) provides in-built features to ease the process of writing code for certain types of requirements. The above approaches range from simple to complex programming paradigms depending on how to fetch the operation. Also, C++ provides various other methods that can be used to normalize or complicate the output. The above codes can also be changed to make various other calculators like a Scientific Calculator which has infinite usage in the higher mathematical calculations.


Related Topics

Full Form of IG

IG Full Form Many of us might get confused between DGP and IG. We think that both are the same. Well, that’s true. Both DGP and IG are the almost same...

3 minutes read.

Full Form of VIP

Full Form of VIP VIP- Very Important Person The full form of VIP is a very important person or personage. A VIP is a person who has unique entitlement or advantage because...

3 minutes read.

GSLV Full Form

GSLV Full Form: GSLV (Geosynchronous Satellite Launch Vehicle) is a launcher vehicle used to launch satellites, spacecraft and other space objects to Geosynchronous Transfer Orbit. It is made by ISRO...

7 minutes read.

Full Form of CIDR

CIDR is a short form that stands for Classless Inter-Domain Routing. It is a technique for allocating IP addresses that boosts the effectiveness of address distribution. Super netting is another...

3 minutes read.

Full Form of BBC

BBC 1. BBC- British Broadcasting Corporation BBC refers to a British broadcasting corporation. It is a mass media industry founded on 18 October 1922. It is a public service broadcaster which has...

4 minutes read.

Full Form of IUPAC

IUPAC stands for International Union of Pure and Applied Chemistry. It is an international non-government organization with the purpose of solving many global issues involving the chemical sciences. The organization's...

4 minutes read.

Full Form of SOS

SOS Full Form SOS stands for “Save Our Souls” or “Save Our Ship”. But officially there is not any full form for the abbreviation. It is just a distinctive Morse code...

5 minutes read.

Full Form of RSVP

RSVP FULL FORM The full form of RSVP is Répondez S’il Vous Plaît. It is an initialism that means please respond. It is a French phrase that is used to get...

4 minutes read.

Full Form of LCD

LCD Full Form Whenever we go to buy some electronic gadgets, we come across terms like LCD and LED. But what do they mean? For instance, we know that both are...

3 minutes read.

Calculator Program in C++

Calculator Program in C++ A calculator program is a simple instructional and case action program that does numerical calculations. We can carry out simple to complex operations depending on the type...

5 minutes read.

Full Form Of IS

IS stands for Indian services. Now, the question arises, what are Indian services? Indian services refer to All India Services, which is the backbone of our country. All India Services include...

5 minutes read.

full form of PAN

What is the full form of PAN PAN: Permanent Account Number PAN is an abbreviated form of Permanent Account Number. PAN is an identification number that usually consists of ten characters, mainly alphanumeric....

6 minutes read.

Full form of IPO

What is the Full form of IPO IPO: Initial Public Offering IPO stands for Initial Public Offering. It is a procedure through which a company can go public; in this, the company...

4 minutes read.

FICCI Full Form

FICCI Full Form FICCI means Federation of India Chambers of Commerce and Industry. It is a non-government and non- profitable trade organisation that promotes India's business and industry. FICCI was founded in...

3 minutes read.

Full Form of SMS

Full Form of SMS SMS stands for the Short Message Service. It is a service that sends short text messages. The standardized communication protocols are used by SMS for this...

6 minutes read.

Full form of SI

What is the full form of SI SI: Sub-Inspector SI stands for Sub-Inspector. It is a rank that is mainly used by Police of South Asia- namely by Bangladesh, India, Pakistan, and...

5 minutes read.

Full Form of IMF

IMF (International Monetary Fund) The International Monetary Fund (I.M.F.) is an organization located in Washington, D.C. It consists of "189 countries trying to cultivate global fiscal cooperation, secure solidity involving money,...

5 minutes read.

Full Form of CEO

Full Form of CEO CEO is the most desirable and powerful position longed by every individual. But most of our youngsters and even adults are not aware of its full form. The...

3 minutes read.

Full Form of DVD

DVD Full Form DVD stands for Digital Versatile Disc or Digital Video Disc. It is a digital optical disc that is used for storing data. This hardware was developed in 1995...

7 minutes read.

Full Form of DRDO

Full Form of DRDO Do you know that the development and advancement of our Defence services rely on the shoulders of the DRDO organization. Let’s see what does DRDO stands for. The...

4 minutes read.