java - Q: Simple Loop Tracing -
i'm not sure happens "num2", "num1" times every number 1-4 times every number 1-4 have no idea "num2"
int num1 = 0; int num2 = 0: (var = 0; <= 4; i++){ num1 = * i; num2 += num1; system.out.println(num1 + " "); } system.out.println(num2);
so question trace "num2"? appreciated!
in case, following true:
num1 equal whatever index is, multiplied itself. therefore run on 0, 1, 2, 3 , 4 starts 0 , runs until less or equal 4.
therefore, num1 be:
1) 0 * 0 = 0 2) 1 * 1 = 1 3) 2 * 2 = 4 4) 3 * 3 = 9 5) 4 * 4 = 16
then num2 calculates sum of each of these, be:
0 + 1 + 4 + 9 + 16 = 30
this broken into:
before loop: num2 = 0 1) num2 = 0 + 0 = 0 2) num2 = 0 + 1 = 1 3) num2 = 1 + 4 = 5 4) num2 = 5 + 9 = 14 5) num2 = 14 + 16 = 30
it adding whatever num1 total far.
hope clarifes bit.
edit:
as sharonbn has mentioned, var not valid type in java, should 'int'.
also, have:
int num2 = 0:
here have ended colon (:) should semi-colon (;).
Comments
Post a Comment