Switch Statement is used, when you have multiple definite conditions.
Understanding of Switch Statement
When you use the Switch statement, first it evaluates the expression. It then looks for the first case clause whose expression evaluates the same value as the result of the input expression. then, It executes the associated statements.
If no matching case clause is found, the program looks for the optional default clause, and if found, executes the associated statements.
- The default clause is optional, if person has not entered any valid input then the default statement will be executed.
By convention, the default clause is the last clause, but it does not need to be so.
In the following example,
We are trying to Create a Simple Calculator.
When you Press + then Output will be num1 + num2 i.e. 50+20
When you Press - then Output will be num1 - num2 i.e. 50-20
When you Press * then Output will be num1 * num2 i.e. 50*20
When you Press / then Output will be num1 / num2 i.e. 50/20