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.
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.
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.
Start by including the necessary header files for input/output operations (iostream
) and mathematical functions (cmath
):
#include <iostream>#include <cmath>using namespace std;
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;
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 numbercout << "Enter the first number: ";cin >> num1;// Prompt the user for the operationcout << "Enter an operation (+, -, *, /): ";cin >> operation;// Prompt the user for the second numbercout << "Enter the second number: ";cin >> num2;
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
switch
statementThe 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 zeroif (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
.
if-else
statementThe 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;elsecout << "Error: Division by zero!";} elsecout << "Invalid operator!";
After performing the calculation, we will display the result to the user, but only if there are no errors during the calculation.
// Display the resultif (!error)cout << num1 << " " << operation << " " << num2 << " = " << result << endl;
This will display the result in the format 2 + 3 = 5
.
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');
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
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
or2 + 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 resultdouble num1, num2, result;char operation, choice='\0';bool error=false;do{error=false;// Prompt the user for the first numbercout << "Enter the first number: \n";cin >> num1;// Prompt the user for the operationcout << "Enter an operation (+, -, *, /): \n";cin >> operation;// Prompt the user for the second numbercout << "Enter the second number: \n";cin >> num2;// Perform the calculation based on the chosen operationswitch (operation) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':// Check for division by zeroif (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 resultif(!error)cout << num1 << " " << operation << " " << num2 << " = " << result << endl;// Ask if the user wants to perform another calculationcout << "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.
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!
Haven’t found what you were looking for? Contact Us
Free Resources