Switch case in C: solved exercise with interactive menu
Switch case in C: solved exercise step by step
If you searched for a solved switch case exercise in C, here is the most common pattern: an interactive menu with several options and a default case for invalid input.
switch is the natural alternative to a chained if-else when comparing the same integer (or character) variable against multiple constant values.
Problem statement
Write a program that implements a basic console calculator. The user selects an operation from a numbered menu (1–4) and enters two operands. The program prints the result and warns on invalid options or division by zero.
C solution
Expected output
With inputs 1, 3.0, 4.0:
Common mistakes
- Forgetting
breakat the end of eachcase: without it, execution falls through to the next case. - Using non-constant or floating-point expressions as
caselabels (does not compile). - Omitting
defaultand leaving invalid input unhandled. - Trying to use
switchwith strings: it only works with integer types (int,char,enum).
When to use switch instead of if-else
| Situation | Prefer |
|---|---|
| Comparing one variable against many constants | switch |
| Range checks or complex expressions | if-else |
| Comparing strings | if-else with strcmp |
| Two or three branches | either |
Practical use
switch appears in:
- console menus and state machines,
- command or keystroke processing,
- decoding error codes or operation codes.
Recommended next exercise
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
What is fall-through in switch?
If there is no break at the end of a case, execution continues into the next case even if its label does not match. This can be intentional to share code between cases, but is usually a bug.
Can switch compare strings in C?
No. switch only works with integer types (int, char, short, long, enum). To compare strings use if-else with strcmp.
Is switch faster than if-else?
With many cases, many compilers compile switch as a jump table, which can be faster than a chain of if-else. With few branches the difference is negligible.