C++ switch...case Statement
C++ switch...case Statement
The nested if ...else statement allows you to execute a block code among many alternatives. if you are checking on the value of a single variable in nested if.... else statement, it is better to use switch statement.
The switch statement is often faster than nested if....else (not always). Also, the syntax of switch statement is cleaner and easier to understand.
C++ switch......case syntax
When a case constant is found that matches the switch expression, control of the program passes to the block of code associated with that case.
In the above pseudocode, suppouse the value of n is equal to constant2. The compiler will execute the block of code associated with the case statement until the end of switch block, or until the break ststement is encountered.
The break statement is used to prevent the code running in to the next case.
Flowchart of switch Statement
Example: C++ switch Statement
Output
The - operator entered by the user is stored in o variable. And, two operaands 2.3 and 4.5 are stored in variables num1 and num2 respectively.
Then the control of the program jumps to
Then the control of the program jumps to
Finally, the break statement ends the switch statement.
if break statement is not used, all cases after the correct case is executed.
0 comments:
Post a Comment