C++ Tutorial
C++ Project: Calculator
A four-function calculator with functions per operator and a check for divide-by-zero.
What you will build
This project is a four-function calculator: add, subtract, multiply, and divide. Each operator lives in its own function so the arithmetic is not copied into every branch. Division checks the divisor before it runs. A zero divisor prints a message instead of crashing or printing infinity.
The examples use hardcoded numbers so they compile and print at once. Click Try it in C++ to open /cpp/try. That editor is g++ in the browser. After the logic is clear, you can replace the literals with cin.
One function per operator
A function has a return type, a name, and parameters. Put helpers above main so the compiler has already seen them when main calls them. Each operator takes two double values and returns a double. Using double keeps 10 divided by 4 as 2.5, not 2.
Example
#include <iostream>
using namespace std;
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
int main() {
cout << add(10.0, 4.0) << endl;
cout << subtract(10.0, 4.0) << endl;
return 0;
}Output is 14 then 6. Change 10.0 to 3.5 and compile again. The function bodies stay the same; only the arguments change.
Multiply and a named result
Store the return value when you need it more than once, or when you want a name that documents the meaning.product is easier to read in a print line than a nested call.
Example
#include <iostream>
using namespace std;
double multiply(double a, double b) {
return a * b;
}
int main() {
double product = multiply(10.0, 4.0);
cout << "10 * 4 = " << product << endl;
return 0;
}Use Try it in C++ under the example so the program opens at /cpp/try. The Python editor at /try will not compile this file.
Guard divide-by-zero
Division by zero is not a useful result for a calculator. Check the divisor first. This version returnsfalse when the divisor is zero and writes the quotient through a reference only when the division is safe. main then decides what to print.
Example
#include <iostream>
using namespace std;
bool divide(double a, double b, double& result) {
if (b == 0.0) {
return false;
}
result = a / b;
return true;
}
int main() {
double q = 0.0;
if (divide(10.0, 4.0, q)) {
cout << "10 / 4 = " << q << endl;
} else {
cout << "Cannot divide by zero" << endl;
}
if (divide(10.0, 0.0, q)) {
cout << "10 / 0 = " << q << endl;
} else {
cout << "Cannot divide by zero" << endl;
}
return 0;
}The first call prints 10 / 4 = 2.5. The second call prints the error line. q is not updated on failure, so a later print of q would still show the last successful quotient.
Complete calculator
Pick an operator with a char and an if / else if chain. Call the matching function. Unknown operators get their own message. This program runs five hardcoded cases so you can see every branch without typing.
Example
#include <iostream>
using namespace std;
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
bool divide(double a, double b, double& result) {
if (b == 0.0) {
return false;
}
result = a / b;
return true;
}
void calculate(double a, char op, double b) {
cout << a << " " << op << " " << b << " = ";
if (op == '+') {
cout << add(a, b) << endl;
} else if (op == '-') {
cout << subtract(a, b) << endl;
} else if (op == '*') {
cout << multiply(a, b) << endl;
} else if (op == '/') {
double q = 0.0;
if (divide(a, b, q)) {
cout << q << endl;
} else {
cout << "Cannot divide by zero" << endl;
}
} else {
cout << "Unknown operator" << endl;
}
}
int main() {
calculate(10.0, '+', 4.0);
calculate(10.0, '-', 4.0);
calculate(10.0, '*', 4.0);
calculate(10.0, '/', 4.0);
calculate(10.0, '/', 0.0);
calculate(10.0, '%', 4.0);
return 0;
}The last line is not remainder. This calculator does not implement %, so that case printsUnknown operator. Keep the operator set small until the four functions are solid.
Later, typed input can replace the hardcoded calls with cin >> a >> op >> b;inside a loop. Leave that until the functions and the zero check already work.
Common mistakes
- Using
intfor both operands. Integer division turns 10 / 4 into 2. Stay withdoubleunless you want truncating division on purpose. - Checking the divisor after the division. The test must run first. An
ifaftera / bis too late. - Comparing operators with a string.
opis achar. Write'/', not"/". - Forgetting a reference on the divide result. Without
&,resultis a copy andmainnever sees the quotient.
Practice
- Add a power function that returns
araised to an integer exponent using a loop, not a library call. - Print each successful result with two digits after the decimal. Include
<iomanip>and usefixedwithsetprecision(2). - Reject a second operand of zero for both divide and remainder if you add remainder, and print which operator failed.
Next project: a roster of students in a vector of structs, with a printed list and a top score.