Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Confused by increments

Fitz Herbert
Greenhorn
Posts: 21
Having a few problems with a question involving increments within loop/switch statements.
The question code is as follows
which prints 356
WHY?
I realized that the case statement '0'is not caught
my reasoning a bit iffy
then i looked at the increments and started to lose
track

John Lee
Ranch Hand
Posts: 2545
Originally posted by Fitz Herbert:
Having a few problems with a question involving increments within loop/switch statements.
The question code is as follows
which prints 356
WHY?
I realized that the case statement '0'is not caught
my reasoning a bit iffy
then i looked at the increments and started to lose
track

i is int, so i fail the case of "0", in switch statement, is says "i++", so in next loop, i become 2+1=3. so it skip i=2 case.

Greg Charles
Sheriff
Posts: 2994
12
I really hate problems like this. Asking what happens when intentionally confusing code is written loses the point that you should always strive for clarity.
Anyway, here's what is happening:
The first time the switch statement is hit, the value of i is 0. That doesn't match any of the case statments. It doesn't match '0', because that is a character, and when view as an integer, its value is 48, the ASCII value of the character 0. Therefore nothing is printed.
i is incremented twice, once by the incrementer in the switch statement, then by the for loop incrementer. The next switch uses a value of i = 2. That matches a case, so "3" is printed out. (Did I mention I hate this code.)
i is incremented twice more, so it has a value of 4. That matches a case so "5" is printed out. There is no break, so execution falls through to the case 'E' as well and prints out "6". The value of i after the switch is 5, so the loop terminates and we're done.

William Barnes
Ranch Hand
Posts: 986
I really hate problems like this.

Exactly, why would anyone write code in which the 'case' for 1 prints 2?

Layne Lund
Ranch Hand
Posts: 3061
Originally posted by William Barnes:

Exactly, why would anyone write code in which the 'case' for 1 prints 2?

To be obnoxious? Or maybe they are trying to write test questions for the SCJP exam...
[ May 19, 2003: Message edited by: Layne Lund ]

John Lee
Ranch Hand
Posts: 2545
that is what i figured..

Fitz Herbert
Greenhorn
Posts: 21
Hello
SCJ2 questions
thankyou for the response

Greg Charles
Sheriff
Posts: 2994
12
Originally posted by Layne Lund:

To be obnoxious? Or maybe they are trying to write test questions for the SCJP exam...

That doesn't sound like an "either-or" situation to me!

Layne Lund
Ranch Hand
Posts: 3061
Originally posted by Greg Charles:

That doesn't sound like an "either-or" situation to me!

*ROFL* Thanks for cheering me up for the day.