Java,How it works for loop | SoloLearn: Learn to code for FREE!

+1

Java,How it works for loop

isnt it like this, i = 7;7 < 49;--7 how it runs? https://code.sololearn.com/cb72I9oUK6Ej/?ref=app

6/28/2019 3:38:50 AM

Tzion

7 Answers

New Answer

+2

Rael Well yes, but that is the case if you write it down like this for(int i = 7;i < i*i;){ System.out.print(--i); } The --i in the loop is actually a single separate statement. If you break it down, it would be like this for(int i = 7;i < i*i;){ System.out.print(i); --i; } Therefore, changing it to i-- won't have any effect nb. The third statement in for loop is executed after the code execution

+4

Rael That will be the case for first iteration. For 2nd iteration i value becomes 6 then condition will be like i < i*i = 6 < 36; --6 then 5 < 25 and so on till i reaches 1. when that happen you will have 1 < 1*1 = false and the loop exits. Thanks to Agent_I for pointing out the silly mistake.

+3

~ swim ~ I think it's until the i reaches 1 not 0, because 1 < 1 is false

+3

Agent_I yes you are right, overlooked it. Thanks for correcting. I'll update my answer 👍

+2

System.out.printf("i=%d i*i=%d\n", i, i*i); i=7 i*i=49 i=6 i*i=36 i=5 i*i=25 i=4 i*i=16 i=3 i*i=9 i=2 i*i=4

+2

result of --i and i-- is same value, but there is different behaviour when decrementing variable is assigned or used as parameter. for(int i=7,ii=7; i< i*i; ){ System.out.printf("--i %d ii-- %d assigning\n", --i, ii--); System.out.printf("%5d %5d after\n\n", i, ii ); } --i 6 ii-- 7 assigning 6 6 after --i 5 ii-- 6 assigning 5 5 after --i 4 ii-- 5 assigning 4 4 after ...

+1

~ swim ~ Agent_I zemiak Thank you! One thing i dont understand is --i or i-- they both will output same in this code ,why? isn't the --i will decrease 1 first before print it out?