PPractick

DSA interview question

Switch Case: Mini Calculator

Easy · Algorithms · Topics: language basics

The problem

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".

Function signature

string calculate(long long a, long long b, char op);  // result as text, or an error message

Test cases

Input (a, b, op)OutputExplanation
(7, 3, '+')10Addition
(7, 10, '-')-3Negative result
(6, 7, '*')42Multiplication
(7, 2, '/')3Integer division truncates
(-7, 2, '/')-3Truncates toward zero in C++
(7, 3, '%')1Remainder
(7, 0, '/')Error: division by zeroGuarded instead of crashing
(7, 2, '^')Error: unknown operatorFalls to default

(Confirm: integer arithmetic only; results fit in a long long; unknown operators return an error string.)

How interviewers phrase it

Clarifying questions to ask

  1. Are the numbers integers or decimals? (Changes how / and % behave.)
  2. What should happen on division by zero: return an error, throw, or print a message?
  3. Which operators must be supported, and what should an unsupported one do?
  4. Can the inputs be large enough to overflow on multiplication?

Follow-ups to expect

  1. "What happens if you leave out break?"
  2. "Can you switch on a string in C++?"
  3. "Why can't I declare a variable inside a case without braces?"
  4. "When is switch better than if-else?"
  5. "Where does default go?"
  6. "How does C++ integer division treat negative numbers?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in