In this tutorial, we will be creating a simple calculator using C++ programming language.
The calculator will be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
To get started, we will first create a C++ file called “calculator.cpp” and include the necessary header files:
#include<iostream> #include<cmath> using namespace std;
The iostream header file is used for input and output operations, while the cmath header file is used for mathematical functions such as sqrt(), pow(), etc.
Next, we will declare the main function and declare the variables needed for our calculator.
In this case, we will declare two variables for the operands and one variable for the operator.
We will also ask the user to enter the operator and the operands:
int main() { double num1, num2; char op; cout << "Enter operator (+, -, *, /): "; cin >> op; cout << "Enter two operands: "; cin >> num1 >> num2;
After getting the necessary inputs from the user, we will use a switch statement to perform the corresponding arithmetic operation based on the operator entered by the user.
We will display the result of the operation to the user using the cout statement:
switch(op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; default: // If the operator is not valid cout << "Invalid operator"; break; }
Finally, we will return 0 to indicate that the program has run successfully and end the program:
return 0; }
Putting it all together, our complete C++ program to create a simple calculator looks like this:
#include<iostream> #include<cmath> using namespace std; int main() { double num1, num2; char op; cout << "Enter operator (+, -, *, /): "; cin >> op; cout << "Enter two operands: "; cin >> num1 >> num2; switch(op) { case '+': cout << num1 << " + " << num2 << " = " << num1 + num2; break; case '-': cout << num1 << " - " << num2 << " = " << num1 - num2; break; case '*': cout << num1 << " * " << num2 << " = " << num1 * num2; break; case '/': cout << num1 << " / " << num2 << " = " << num1 / num2; break; default: // If the operator is not valid cout << "Invalid operator"; break; } return 0; }
In conclusion, creating a simple calculator in C++ involves getting the necessary inputs from the user, performing the corresponding arithmetic operation using a switch statement, and displaying the result to the user.
This tutorial has covered the basics of creating a simple calculator using C++ programming language.