← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 15 of 17

C++ Mini Project — Calculator

Structuring Operations

Splitting each math operation -- addition, subtraction, multiplication, division -- into its own small function keeps the calculator's logic organized and testable individually, rather than tangled together inside one large block of conditional branches.

Example: Structuring Operations

cpp
#include <iostream>

double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }

int main() {
	std::cout << add(3, 2) << " " << subtract(3, 2) << std::endl;
	return 0;
}

Designing the Menu

A text-based menu prints the available operations and reads the user's choice, translating that input into which function gets called next -- this is the control-flow backbone that ties the individual operation functions together into a usable program.

Example: Designing the Menu

cpp
#include <iostream>

int main() {
	int choice = 1;
	std::cout << "1. Add\n2. Subtract" << std::endl;
	if (choice == 1) std::cout << "Add selected" << std::endl;
	return 0;
}

Guard Against Division by Zero

Dividing by zero is undefined behavior for integers (and produces infinity or NaN for floating-point), and can crash or silently corrupt a program's output. Checking that the divisor isn't zero before performing division, and reporting a clear error instead, is a mandatory safeguard in any calculator.

Example: Guard Against Division by Zero

cpp
#include <iostream>

double safeDivide(double a, double b) {
	if (b == 0) {
		std::cout << "Cannot divide by zero" << std::endl;
		return 0;
	}
	return a / b;
}

int main() {
	std::cout << safeDivide(10, 0) << std::endl;
	return 0;
}

Storing Calculation History

Storing each calculation's inputs and result in a std::vector as they happen lets you build a history feature -- printing every previous calculation back to the user on request, without needing to persist anything to disk.

Example: Storing Calculation History

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<double> history;
	history.push_back(3 + 2);
	history.push_back(10 - 4);
	for (double result : history) std::cout << result << " ";
	std::cout << std::endl;
	return 0;
}

Continuous Calculation Flow

Feeding a calculation's result back in as the input to the next operation (rather than starting fresh each time) lets users chain a sequence of operations together, the same way a physical calculator's running total works.

Example: Continuous Calculation Flow

cpp
#include <iostream>

int main() {
	double result = 5;
	result = result + 3;
	result = result * 2;
	std::cout << result << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.