How to make a calculator in C++

Key takeaways:

  • C++ provides several ways to create calculators, including switch or if-else statements.

  • The switch method is straightforward for specific operators like +, -, *, /.

  • The if-else method offers flexibility for handling more conditions or complex logic.

  • Input validation ensures division by zero or invalid operations are handled gracefully.

  • A loop allows users to perform multiple calculations until they opt to exit.

A calculator is a fundamental tool used in various applications to perform arithmetic operations quickly and efficiently. Building a simple calculator in C++ can be an excellent way to practice programming skills and understand the basics of handling user inputs, performing calculations, and displaying results. Let’s walk through the process of creating a basic calculator in C++. This calculator will be able to perform addition, subtraction, multiplication, and division on two numbers provided by the user.

Setting up the project for the calculator

To begin, ensure you have a C++ compiler installed on your system. Once you have a compiler ready, create a new C++ project or simply create a new .cpp file to write your calculator program.

Including headers

Start by including the necessary header files for input/output operations (iostream) and mathematical functions (cmath):

#include <iostream>
#include <cmath>
using namespace std;

Declaring variables

At the beginning of the program, we need to declare the variables that will store the user inputs and the result of the calculation. We will use the double data type for the numbers to handle decimal inputs. Additionally, we’ll use a char variable called the operation to store the arithmetic operation chosen by the user, and a char variable called choice to determine if the user wants to perform another calculation after one is completed. Finally, we will have a boolean variable named error to store if an error occurred or not.

double num1, num2, result;
char operation, choice = '\0';
bool error = false;

Getting the user input

We will prompt the user to enter the first number, the operation they want to perform, and the second number. Here is the code for taking user input:

// Prompt the user for the first number
cout << "Enter the first number: ";
cin >> num1;
// Prompt the user for the operation
cout << "Enter an operation (+, -, *, /): ";
cin >> operation;
// Prompt the user for the second number
cout << "Enter the second number: ";
cin >> num2;

Perform the calculation

There are several methods to make a calculator in C++. In this Answer, we’ll discuss two different approaches to perform the calculation:

  • Using switch statement

  • Using if-else statement

Using the switch statement

The switch statement allows us to handle different cases based on the value of the operation variable.

switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
// Check for division by zero
if (num2 != 0)
result = num1 / num2;
else {
cout << "Error: Cannot divide by zero." << endl;
error=true;
}
break;
default:
cout << "Error: Invalid operation." << endl;
error=true;
break;
}

In this snippet, we calculate the result based on the chosen operation and store it in the result variable. We handle the special case of division by zero to avoid potential errors and provide an appropriate error message. We also set the error to true.

Using the if-else statement

The if-else approach is more flexible and can handle conditions not covered by switch.

if (operation == '+')
cout << "Result: " << num1 + num2;
else if (operation == '-')
cout << "Result: " << num1 - num2;
else if (operation == '*')
cout << "Result: " << num1 * num2;
else if (operation == '/') {
if (num2 != 0)
cout << "Result: " << num1 / num2;
else
cout << "Error: Division by zero!";
} else
cout << "Invalid operator!";

Display the result

After performing the calculation, we will display the result to the user, but only if there are no errors during the calculation.

// Display the result
if (!error)
cout << num1 << " " << operation << " " << num2 << " = " << result << endl;

This will display the result in the format 2 + 3 = 5.

Ask for another calculation

We’ll ask the user if they want to perform another calculation. If the user chooses to continue, the loop will repeat, otherwise, the program will exit.

cout << "Do you want to perform another calculation? (y/n): ";
cin >> choice;

The do-while loop can be used to ensure that the user can keep using the calculator until they decide to quit by entering 'n' or 'N'.

if (choice == 'n' || choice == 'N') {
cout << "Exiting the calculator. Thank you for using it!" << endl;
}
} while (choice == 'y' || choice == 'Y');

Exit the program

Once the user decides to stop using the calculator, the loop will terminate, and the program will exit, indicating successful completion.

return 0; // Exit the program successfully

Running the calculator

Save your code and compile it using your C++ compiler. For instance, using GCC:

g++ calculator.cpp -o calculator

Once compiled successfully, run the executable:

./calculator

We will use switch statement to implement the calculator. Here is the complete code:

Note: Enter input in format 2 + 3 n or 2 + 3 y 4 - 2 n for multiple calculations in single execution.

#include <iostream>
#include <cmath>
using namespace std;
int main() {
// Declare variables to store user inputs and result
double num1, num2, result;
char operation, choice='\0';
bool error=false;
do{
error=false;
// Prompt the user for the first number
cout << "Enter the first number: \n";
cin >> num1;
// Prompt the user for the operation
cout << "Enter an operation (+, -, *, /): \n";
cin >> operation;
// Prompt the user for the second number
cout << "Enter the second number: \n";
cin >> num2;
// Perform the calculation based on the chosen operation
switch (operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
// Check for division by zero
if (num2 != 0)
result = num1 / num2;
else {
cout << "Error: Cannot divide by zero." << endl;
error=true;
}
break;
default:
cout << "Error: Invalid operation." << endl;
error=true;
break;
}
// Display the result
if(!error)
cout << num1 << " " << operation << " " << num2 << " = " << result << endl;
// Ask if the user wants to perform another calculation
cout << "Do you want to perform another calculation? (y/n): \n";
cin >> choice;
if (choice == 'n' || choice == 'N') {
cout << "Exiting the calculator. Thank you for using it!" << endl;
}
} while (choice == 'y' || choice == 'Y');
return 0; // Exit the program successfully
}

Enter the input below

This calculator allows users to perform basic arithmetic operations on two numbers and keeps running until the user decides to quit. You can build upon this foundation to add more functionality or improve the user experience as per your requirements.

Conclusion

Building a calculator in C++ is a great way to practice core programming concepts. Start with basic arithmetic operations and expand it to include loops and advanced features like functions or error handling. With practice, you can create more complex and user-friendly calculators.

Unlock the world of programming from our C++ course: Learn C++ from Scratch, which is perfect for beginners looking to build a solid foundation in coding!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to make a calculator by C++?

You can create a calculator in C++ using switch or if-else statements to handle operations like addition, subtraction, multiplication, and division. Collect user input, perform calculations based on the chosen operation, and display the result.


Is it hard to code a calculator?

No, creating a simple calculator is not difficult and is an excellent way to practice basic programming concepts like input/output, condition handling, and loops.


Is it possible to create an app using C++?

Yes, C++ can be used to create applications, including desktop, mobile, and even embedded system apps, thanks to its versatility and performance.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved