Loading lessons...
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
charin one go - Choosing a branch with
switch - Using
breakto 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
- After reading
op, open aswitch (op)block. - Add
case '+':and print(a + b), thenbreak;. - Do the same for
case '-':,case '*':, each with its ownbreak;. - For
case '/':use anif: ifb == 0printCannot divide by zero., else print(a / b). - Add
default:to printUnknown operator. - Compile and try
10 / 2,10 / 0, and2 + 3.
Checklist
- [ ]
switchuses the operator character - [ ] Each case prints the correct result
- [ ] Each case ends with
break; - [ ] Division by zero prints a message instead of crashing
- [ ]
defaultcatches unknown operators - [ ] The program compiles and runs
TL;DR
switchpicks a branch based on the value of achar.- Every case should end with
break;or execution falls through. - Guard division by zero with an
ifbefore dividing. defaulthandles everything no case matched.