C++ Tutorials
Tutorials
C++C++ Decision Making Statements
switch statement
switch statement:
If there are a number of decision making conditions instead of making an if….else construct, the programmer can use switch statement.
The general syntax is:
|
In the above example, the expression is first evaluated and the value id checked with the constant1 in the case statement. If this is evaluated with the same value, then the group of statements is executed. When a break statement is encountered, the control is switched to the end of the switch statement. If the value of the expression is not equal to connstant1, it is checked with constant2. If it evaluates the same value, then the group of statements (in the case of constant2) are executed. When a break statement is encountered, the control is then switched to the end of the switch statement. This proceeds until the value of expressions equal one of the constant values given. If the value of the expression is not equal to any of the constant values given, then, by default, the statements present are executed.
For example:
|
In the above example, the output produces:
- Enter Input Value:10
- Value is 10
Since the entered input is 10, which is equal to the first case value, the statement in the first case block is executed.
- Enter Input Value:50
- Invalid Input
Since the entered input is 50, which is not equal to any of the case values, the default statement is executed.
Suppose the programmer wants the same block of statements to be executed for a number of case values. This is performed by removing the break statement. If a break statement is removed, then the control inside the end of a switch statement will move to the next case statement and proceed until it finds a break statement.
Important care must be taken not to place variables in case values. Only constants can be placed and expressions of the switch statement can be compared only with constants in case statements.
conditional operator:
As we have seen before in the earlier chapter covering operators in C++, the conditional operator actually is a form of if…else statement.
|
could be written using conditional operators as
|
First Page: C++ Decision Making Statements
Comments
salman said:
| it is very good web |
