The Conditional Operator and the 'switch' Statement

Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.

5. Many-way Branches

Answer:

number += (number % 2 == 1 ) ? 1 : 0 ;

Many-way Branches


    

Often a program needs to make a choice among several options based on the value of a single expression. For example, a clothing store might offer a discount that depends on the quality of the goods:

      • Class 'A' goods are not discounted at all.
      • Class 'B' goods are discounted 10%.
      • Class 'C' goods are discounted 20%.
      • anything else is discounted 30%.

The program fragment does that. A choice is made between four options based on the value in code.

The switch statement looks at the cases to find a match for the value in code.

It then executes the statements between the matching case and the following break. All other cases are skipped. If there is no match, the default case is chosen.

The default case is optional. If present, it must be the last case.

Warning: the complete rules for switch statements are complicated. Read on to get the details.

double discount;      
char code = 'B' ; switch ( code )
{
case 'A':
discount = 0.0;
break; case 'B':
discount = 0.1;
break; case 'C':
discount = 0.2;
break; default:
discount = 0.3;
}

Question 5:

If code is 'C', what is the discount?