Search code examples
javatrace

Q: Simple Loop Tracing


I'm not sure what happens to "num2", I am almost certain that "num1" times every number 1-4 times by every number 1-4 but I have no idea for "num2"

int num1 = 0;
int num2 = 0:

for (var i = 0; i <= 4; i++){
          num1 = i * i;
          num2 += num1;
          System.out.println(num1 + " ");
} 
System.out.println(num2);

So my question is what is the trace for "num2"? Any help is appreciated!


Solution

  • In this case, the following is true:

    num1 will be equal to whatever the index is, multiplied by itself. Therefore this will run on 0, 1, 2, 3 and 4 as your i starts as 0 and runs until it is less than or equal to 4.

    Therefore, num1 will be:

    1) 0 * 0 = 0
    2) 1 * 1 = 1
    3) 2 * 2 = 4
    4) 3 * 3 = 9
    5) 4 * 4 = 16
    

    Then num2 simply calculates the sum of each of these, which would be:

    0 + 1 + 4 + 9 + 16 = 30
    

    This would be broken up into:

    Before for 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 does this by adding whatever num1 was to the total so far.

    Hope this clarifes it a bit.

    EDIT:

    As sharonbn has mentioned, var is not a valid type in java, this should be 'int'.

    Also, you have:

    int num2 = 0:
    

    Here you have ended with a colon (:) this should be a semi-colon (;).