Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do these two code blocks behave differently?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading