Could you explain me please why my code "hangs" when I use short-circuit OR in a loop?
I have written a code to calculate the greatest common factor of two integers:
int a = 9; int b = 6; while (a != 0 || b != 0) //here is the problem { if (a >= b) { a = a - b; } else b = b - a; } if (a == 0) System.out.println(b); else System.out.println(a);
When I use || operator, what seems logical to me in my case, the running of my programme never stops. However, when I use && operator, what seems not logical to me, it works perfectly. Can you explain me please why I cannot exit the loop using the || operator?
By using AND, you're saying "if one is zero, exit the loop." If you use OR, you're saying "if both are zero, exit the loop". It's opposite what you think it is, and that's why you might be confused. When you negate boolean operators like this, AND becomes OR and vice versa. You can learn more about this from DeMorgan's Laws.