Creating a Basic Calculator in C++


In this guide, we will create a simple command-line calculator program in C++. This program will allow users to perform basic mathematical operations such as addition, subtraction, multiplication, and division. We'll provide step-by-step instructions and sample code to help you build your own calculator.


Step 1: Include Required Header

Start by including the necessary header for input and output:


#include <iostream>
using namespace std;

Step 2: Create the Main Function

Create the main function to handle the user interface and calculation. You can use a loop to allow users to perform multiple calculations.


int main() {
char operation;
double num1, num2;
while (true) {
cout << "Enter an operator (+, -, *, /) or 'q' to quit: ";
cin >> operation;
if (operation == 'q' || operation == 'Q') {
break;
}
cout << "Enter two numbers: ";
cin >> num1 >> num2;
switch (operation) {
case '+':
cout << "Result: " << (num1 + num2) << endl;
break;
case '-':
cout << "Result: " << (num1 - num2) << endl;
break;
case '*':
cout << "Result: " << (num1 * num2) << endl;
break;
case '/':
if (num2 != 0) {
cout << "Result: " << (num1 / num2) << endl;
} else {
cout << "Error: Division by zero!" << endl;
}
break;
default:
cout << "Invalid operator!" << endl;
}
}
cout << "Calculator is exiting. Have a great day!" << endl;
return 0;
}

Step 3: Perform the Calculation

Inside the main function, we use a `switch` statement to perform the appropriate mathematical operation based on the operator entered by the user. We also handle division by zero as a special case to prevent runtime errors.


Step 4: Compile and Run

Compile your C++ program using a C++ compiler (e.g., g++) and run the executable. You can now enter mathematical expressions to calculate the results. To exit the calculator, enter 'q'.


Here's how the program works:

  • It prompts the user to enter an operator ('+', '-', '*', '/') or 'q' to quit.
  • It then asks for two numbers.
  • Based on the operator, it performs the corresponding operation and displays the result.
  • If the operator is 'q', the program exits.

Conclusion

Creating a basic calculator in C++ is a simple yet practical exercise that can help you understand fundamental input/output and control flow in C++. You can expand on this project by adding more operations, error handling, and a user-friendly interface.