+ 6

Asking for loop code

need to ask why and how?thank you int j, sum= -44; for(j=0; <=20; j+=5){ sum+=j+1; System.out.println(sum); } Output is:-43,-32,-26,-10,11

26th Feb 2018, 12:36 AM
Sha
Sha - avatar
3 Réponses
+ 18
j will be 0,5,10,15,20 & then loop stops 1st cycle) sum = -44+(0+1)=-43 2nd cycle) sum=-43+(5+1)=-37 3rd cycle)sum= -37+(10+1)=-26 4th cycle)sum= -26+(15+1)=-10 5th cycle)sum=-10+(20+1)=11
26th Feb 2018, 2:29 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 7
oh yes it's -37 and j<=20, sorry for my mistakes!! thank u I think I get it now😀
26th Feb 2018, 1:33 AM
Sha
Sha - avatar
+ 3
Do you mean the output is: -43 -37 -26 -10 11 not -32? And the for loop condition is incomplete, so I'm assuming you meant j<=20, which would make sense then. j = 0 j+1 = 1 -44 +1 = -43 j+=5 (0+5) j = 5 j+1 = 6 -43 + 6 = -37 j+=5 (5+5) j = 10 j+1 = 11 -37 + 11 = -26 j+=5 (10+5) j = 15 j+1 = 16 -26 + 16 = -10 j+=5 (15+5) j = 20 j+1 = 21 -10 + 21 = 11 j+=5 (20+5) j = 25 j is greater than 20 loop exits
26th Feb 2018, 1:15 AM
ChaoticDawg
ChaoticDawg - avatar