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 int for both operands. Integer division turns 10 / 4 into 2. Stay withdouble unless you want truncating division on purpose.
  • Checking the divisor after the division. The test must run first. An if aftera / b is too late.
  • Comparing operators with a string. op is a char. Write '/', not"/".
  • Forgetting a reference on the divide result. Without &, result is a copy andmain never sees the quotient.

Practice

  1. Add a power function that returns a raised to an integer exponent using a loop, not a library call.
  2. Print each successful result with two digits after the decimal. Include <iomanip> and use fixed with setprecision(2).
  3. 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.

FAQ: C++ Project: Calculator

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ calculator project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ calculator project in this C++ C++ lesson (C++ Project: Calculator).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.