Challenge: Tiny Calculator
Completed
Read a whole number, an operator character (+ - * /) and another whole number, like 8 * 3. Print the result. For / use integer division. If the operator is / and the second number is 0, print cannot divide by zero.
Input
Number, operator and number, separated by spaces.
Output
The result, or the divide-by-zero message.
Example
Input
8 * 3
Output
24
Editor
C++
Hints
Read the operator into a char: cin >> a >> op >> b;
switch (op) with case '+': and so on.
Check b == 0 before dividing.
Solution explanation
A char holds the operator, and switch picks the right calculation.
Show solution
#include <iostream>
using namespace std;
int main() {
int a, b;
char op;
cin >> a >> op >> b;
switch (op) {
case '+':
cout << a + b << "\n";
break;
case '-':
cout << a - b << "\n";
break;
case '*':
cout << a * b << "\n";
break;
case '/':
if (b == 0) {
cout << "cannot divide by zero\n";
} else {
cout << a / b << "\n";
}
break;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module