What will be the value of discountRate after the following statements are executed?…
- User
What will be the value of discountRate after the following statements are executed?
double discountRate;
char custType = 'B';
switch (custType)
{
codecase 'A': discountRate = 0.08; break; case 'B': discountRate = 0.06; case 'C': discountRate = 0.04; default: discountRate = 0.0;}
What will be the value of discountRate after the following statements are executed?
double discountRate;
char custType = 'B';
switch (custType)
{
codecase 'A': discountRate = 0.08; break; case 'B': discountRate = 0.06; case 'C': discountRate = 0.04; default: discountRate = 0.0;}
0.04
0.08
0.0
0.06
- Assistant
The answer is 0.0 (zero).
Here's why:
When the switch statement executes with
custType = 'B', it will match the case'B'and execute the code under it. However, since there is nobreak;aftercase 'B':, the execution will "fall through" to the next cases sequentially. Here's how it unfolds:-
case 'B':- Sets
discountRate = 0.06; - No
break;, so it continues to the next case.
- Sets
-
case 'C':- Sets
discountRate = 0.04; - No
break;, so it continues to the next case.
- Sets
-
default:- Sets
discountRate = 0.0; - Execution ends here.
- Sets
As a result,
discountRateis successively assigned0.06, then0.04, and finally0.0. The final value after the switch statement is executed is0.0.Answer: 0.0
-