×

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 CSR

CSR: Corporate Social Responsibility CSR stands for Corporate Social Responsibility. It is a concept of management. As per this concept, the companies combine or merge their social, environmental concerns or issues...

5 minutes read.

Full Form of PCOD

PCOD Full Form We might have heard about PCOD and PCOD. Some of us might think that both PCOD and PCOS are the same. But there are significant differences in both...

3 minutes read.

Full Form Of ISIS

ISIS stands for “Islamic State of Iraq and Syria”. Earlier it was known as ISIL (Islamic State of Iraq and Levant), and now officially known as the Islamic State (IS)....

3 minutes read.

Full Form of IDBI

IDBI Full Form IDBI stands for Industrial Development Bank of India. It is an Indian Government-owned financial service company with the majority of shares. The bank was recategorized as a Private...

3 minutes read.

Full Form of IMAO

IMAO Full Form IMAO stands for In My Arrogant Opinion. It is a slang internet acronym that is similar to LOL (Laugh Out Loud), BTW (By The Way), etc. It is...

3 minutes read.

ECS Full Form

Full Form of ECS- Electronic Clearing Service ECS refers to electronic clearing services. ECS is a scheme of electronic mode. It helps in transferring funds from one bank account to another. This...

4 minutes read.

full form of INR

What is the full form of INR INR: Indian Rupee INR is the abbreviation of Indian Rupee. It is denoted with the sign ?. INR is the Republic of India's official currency. The...

4 minutes read.

Full Form of DSLR

DSLR Full Form What is a DSLR? Many of us have DSLR cameras nowadays, but how many of us know the true meaning or the full form of this abbreviation. Not...

3 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 HIV

Full form of HIV: In the early 90s, the AIDS epidemic caused people to be scared of toilet seats and made sex seem frightful. But since then, people have learned...

5 minutes read.

Full Form of India

Full Form of India India is one of the most densely populated and seventh largest (by land area) countries in the world. With a population of over a billion people, it...

7 minutes read.

Full Form of CBI

Full Form of CBI This tutorial will briefly cover about the various full forms of CBI (Central bureau of Investigation and Central Bank of India) including their definition, history, functions, overviews, vision...

5 minutes read.

Full Form of NEET

Full Form of NEET Many of us may dream of becoming doctor. We all know the gateway of making this dream true is through qualifying the NEET examination.  But have you...

4 minutes read.

Full Form of CMA

Full Form of CMA CMA- Credit Monitoring Analysis CMA is also known as Credit Monitoring Analysis. It is a critical analysis that is done by the credit analyst or a banker to...

5 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.

Full Form of CID

Full Form of CID C.I.D., the famous Television serial drama, is one of the popular shows cherished by Indian spectators for all age groups. The fascinating cases, the murder mysteries, and...

5 minutes read.

Full form of DP

Full form of DP This tutorial will briefly cover about the various full forms of DM, i.e., Display Picture, Data Processing, Display Port, including the meaning of the term, overviews, processes and...

3 minutes read.

Full Form of HR

HR Full Form The employees of the company are the assets to the company. The employees are the invaluable resources through which the company yields profits. The full form of HR...

3 minutes read.

Full Form of BDO

BDO- Block Development Officer BDO stands for Block Development Officer. BDO is the designation of the officer in charge of various matters, activities, and development of the division or the block,...

3 minutes read.

Full Form of HTML

What is HTML? We have heard so much about and even studied HTML in our computer classes. The first thing we were taught was the full form of HTML. Still...

4 minutes read.