# switch statement

Anjali Bahl
Greenhorn
Posts: 7

The output is : 1433

[ August 09, 2004: Message edited by: Barry Gaunt ]

Dan Chisholm
Ranch Hand
Posts: 1865
Anjali,

When you want to ask for help on a question from my web site, then you can post the question here as long as you say that the question came from my web site. When I see one of my questions with the name of the class changed, then it causes me to suspect that you found that question on a web site that has plagiarized my work. In the future, please don't change the name of the class and please specify that the question came from my web site. It would also be nice to provide the URL to the page where the question can be found.

In this case, if that question did not come from my web site, then please tell me where it came from.

The explanation for that question is as follows.

On the first pass through the loop, the switch expression, x, has the value, -5. None of the case constants are matched, so the statement following the default label is executed causing the value of x to be set to -3. On the second pass, the default case of the switch statement is executed again, and two is again added to the value of x. The new value is -1. On the third pass, the value of x is again incremented, and the new value is +1. After that, the value of x is printed on each pass through the loop. For the last two passes, the value of x is 3.

[ August 09, 2004: Message edited by: Dan Chisholm ]

Dedeepya Rao
Greenhorn
Posts: 4
Hi Dan--I also had a doubt on this question about how x gets the value -3 from the expression
default: x += x < 0 ? 2 : -2;
x = x +x and i eavaluated it to -10
Can u correct me if i am wrong--I am sorry to ask something so fundamental.

Dan Chisholm
Ranch Hand
Posts: 1865
Dedeepya,

The expression x += x < 0 ? 2 : -2 can be simplified as follows.

x += ((x < 0) ? 2 : -2);

x += ((true) ? 2 : -2);

x += (2);

x = -5 + 2;

x = -3;

Aarti Dahiya
Greenhorn
Posts: 15
For the first three iterations of the do while loop, the default case of the switch statement executes (x changes from -5 to -3, -1, 1). After the first three iterations x is 1.
In the fourth iteration of the loop, case 1 is executed which PRINTS 1 and changes x to 4. In the fifth iteration, case 4 is executed which PRINTS 4 and changes x to 3.
In the sixth iteration, case 3 is executed which PRINTS 3 and changes success to 1.
In the seventh iteration, case 3 is executed again which PRINTS 3 and changes success to 2.
At this point, success is 2 and x is 3. So, the while condition is false and the loop terminates.
Hence, the output is 1433.