A while statement with no body

Hi,

I’m confused with this while program:

class NoBody {
 public static void main(String args []) {
  int i, j;

   i = 100;
   j = 200;

   while (++i < --j);

   System.out.println("Midpoint is " + i);
 }
}

The book says the output is
Midpoint is 150

Why?

Why doesn’t it produce
Midpoint is 101
Midpoint is 102
up until Midpoint is 150?

Also, is it because ++i is executed before < --j that it ends at 150 and not 149?

Thanks,

Christian

The operations on both operands are taking place in situ. The loop ends when the two values pass each other.

That would be a viable supposition since operations are performed left to right. Note that the comparison does not place until after both operations since math operators have greater precedence than relational operators.

Note also that both operations are PREFIXED, so the math happens before the value is polled by the comparison.

Note also that there actually IS a midpoint since there are initially 101 values in the interval that includes both 100 and 200. Increase 200 by 1 and see what happens. The midpoint is now imaginary since it is between 150 and 151. The code gives us 151 as the midpoint. But that will be the midpoint when we increment 201.


This JS version gives a float when the pointers pass each other.

i = 100
j = 201
while (++i < --j);
console.log(`Midpoint is ${i > j ? (i + j) / 2 : i}`)

Add this line after the current print statement:
System.out.println("Midpoint is " + j);
You’ll see that both variables reach 150 which ends the loop since 150 is not less than 150.

Interestingly enough the term ‘collide’ was my initial choice of word, but I opted for ‘pass’. When they are side by side, but opposite facing in direction, they are at the same point (or crossing the same line).

This while loop will work in JS as well…

i = 100
j = 200
//while (++i < --j)    // logs lower half of list
//while (++i < --j){}  // no body, per se
while (++i < --j);     // end of statement
console.log(`Midpoint is ${i}`)
1 Like

If the either value is odd, ‘pass’ would be appropriate.

1 Like