+ 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

28th Jun 2019, 3:38 AM
Tzion
Tzion - avatar
5 odpowiedzi
+ 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
28th Jun 2019, 8:33 AM
Agent_I
Agent_I - avatar
+ 3
~ swim ~ I think it's until the i reaches 1 not 0, because 1 < 1 is false
28th Jun 2019, 3:54 AM
Agent_I
Agent_I - avatar
+ 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
28th Jun 2019, 4:14 AM
zemiak
+ 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 ...
28th Jun 2019, 9:14 AM
zemiak
+ 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?
28th Jun 2019, 8:22 AM
Tzion
Tzion - avatar