Home > front end >  Why do these two code blocks behave differently?
Why do these two code blocks behave differently?

Time:01-28

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");

CodePudding user response:

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.

CodePudding user response:

The first block works because it is only using > and != operators. This means that the second block must also use > and !=, which makes the statement a non-relational operator.

Precedence ==> && or || then ==> < or > then ==> <= or >= then ==> = then ==> or - then ==> *, /, %, remainder/modulus operator(s)

  •  Tags:  
  • Related