I am not sure as to why these two code blocks are behaving differently. I thought that the problem might have something to do with operator precedence, but I played around with various combinations of parentheses and was unable to change the result.
The first block runs once, but the second block runs three times. Why does the first block not run three times also (for i = 4, 2, and 1)?
for (int i = 4; i > 0 && 4 % i == 0; i--)
System.out.println("hi");
for (int i = 4; i > 0; i--)
if (4 % i == 0)
System.out.println("bye");
>Solution :
It’s because when the condition in the for loop becomes false, the loop will stop running. So the first time 4 % i is not zero, the loop will break and move onto whatever is below it.