-1

I am just starting to study Java and was wondering why the following code

if(x>2) x*=2; if(x>4)x=0; System.out.println(x);

returns 0 for any value of x greater than 2. For example, when x=3, why would 6 not be returned?

SifatR
  • 109
  • 2

1 Answers1

0

Let me rewrite your program in pseudocode:

  1. If $x > 2$ then $x \gets 2x$.
  2. If $x > 4$ then $x \gets 0$.
  3. Print $x$.

Let us denote the value of $x$ at the beginning of line $i$ by $x_i$. If $x_1 > 2$ then the condition $x > 2$ in line 1 holds, and so $x_2 = 2x_1$. But then $x_2 = 2x_1 > 2 \cdot 2 = 4$, and so the condition $x > 4$ in line 2 holds. As a consequence, $x_3 = 0$, and so line 3 prints 0.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503