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 command-line 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;
To perform the calculation based on the chosen operation, we'll use a 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 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
.
After performing the calculation, we will display the result to the user, but only if there were 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'.
do{//code}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
Here is the complete code:
#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;} 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.
Note: Enter input in format
2 + 3 n
or2 + 3 y 4 - 2 n
for multiple calculations in single execution.
Free Resources