DSA interview question
You're building the tiny calculator that sits inside a chat bot. A user sends two whole numbers and an operator character, one of +, -, *, / or %, and the bot replies with the result. Division and remainder by zero must return a friendly error instead of crashing the bot, and any other character must be reported as an unknown operator. Since the operator is a single character with a handful of possible values, this is the textbook use case for a switch statement.
Example: calculate(7, 3, '+') → "10", calculate(7, 0, '/') → "Error: division by zero".
string calculate(long long a, long long b, char op); // result as text, or an error message
Input (a, b, op) | Output | Explanation |
|---|---|---|
(7, 3, '+') | 10 | Addition |
(7, 10, '-') | -3 | Negative result |
(6, 7, '*') | 42 | Multiplication |
(7, 2, '/') | 3 | Integer division truncates |
(-7, 2, '/') | -3 | Truncates toward zero in C++ |
(7, 3, '%') | 1 | Remainder |
(7, 0, '/') | Error: division by zero | Guarded instead of crashing |
(7, 2, '^') | Error: unknown operator | Falls to default |
(Confirm: integer arithmetic only; results fit in a long long; unknown operators return an error string.)
break in a switch?"/ and % behave.)break?"switch on a string in C++?"case without braces?"switch better than if-else?"default go?"On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in