Switch Case Statement in C++
Introduction
The switch statement is a control statement in programming (like C, C++, Java) that is used to execute one block of code out of many options based on the value of a variable or expression.
Instead of writing many if–else conditions, we use a switch statement when we need to compare one variable with multiple fixed values.
Why we use switch statement?
-
Makes code cleaner and easier to read
-
Better than long if–else ladder
-
Useful when choices are fixed values (menu, days, options, etc.)
How switch statement works
-
The expression is evaluated once.
-
Its value is compared with each case.
-
When a match is found, that case block is executed.
-
break stops execution and exits the switch.
-
If no case matches, the default block runs.
Output:
The break Keyword
break keyword is used to immediately stop the execution of a loop or a switch statement and transfer control outside of it.Example (with break)
Output:



Comments
Post a Comment