Lesson 59 +30 XP

Project 3: Basic Calculator

Project 3: Basic Calculator

A calculator is the classic way to practice switch. You feed in two numbers and one operator, and the program picks the matching branch - even when the operator is / and the second number is 0.

The goal

Prompt for two numbers and an operator (+, -, *, or /), then print the result. Division by zero must be handled cleanly.

What you practice

  • Reading two numbers and a char in one go
  • Choosing a branch with switch
  • Using break to stop a case
  • Guarding division by zero with an if

Starter code

This compiles as-is:

#include <iostream>
using namespace std;

int main() {
  double a, b;
  char op;
  cout << "Enter two numbers: ";
  cin >> a >> b;
  cout << "Enter an operator (+ - * /): ";
  cin >> op;
  cout << a << " " << op << " " << b << endl;
  return 0;
}

Step-by-step

  1. After reading op, open a switch (op) block.
  2. Add case '+': and print (a + b), then break;.
  3. Do the same for case '-':, case '*':, each with its own break;.
  4. For case '/': use an if: if b == 0 print Cannot divide by zero., else print (a / b).
  5. Add default: to print Unknown operator.
  6. Compile and try 10 / 2, 10 / 0, and 2 + 3.

Checklist

  • [ ] switch uses the operator character
  • [ ] Each case prints the correct result
  • [ ] Each case ends with break;
  • [ ] Division by zero prints a message instead of crashing
  • [ ] default catches unknown operators
  • [ ] The program compiles and runs

TL;DR

  • switch picks a branch based on the value of a char.
  • Every case should end with break; or execution falls through.
  • Guard division by zero with an if before dividing.
  • default handles everything no case matched.