Ram Bhatti Ram Bhatti - 12 days ago 8
Java Question

Just Making Sure

I am new to JAVA and I have to use paper and a pencil to create a variable trace for the following code, tracing the values of

num1, num2, i, and any output
. This is the code I have to trace:

int num1 = 0;
int num2 = 0:

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


This is my first trace I have no idea what the format is. This is what I have done so far:

Variable i Variable num1 Variable num2 Output
0 0 0 0
1 1 1 1
2 4 4 5
3 9 9 14
4 16 16 30
5 False Condition 30


(1) When
i=0
num1 is also 0 because
num1 = i * i;


And to find num2 we do
num2 += num1;
which also makes it 0.

(2) When
i=1
num1 is also 1 because
num1 = i * i;


And to find num2 we do
num2 += num1;
which also makes it 1.

And so on

For the output, when it adds
(num2+=num1)
the value of num2 remains. So, it adds num1 value with the previous output. So, even though num2 and output are the same the value is different but they both display 30 at the end and when you add all values of num2 it adds up to 30. So, it would display
0, 1, 4, 9, 16, 30.


I just want to make sure that I have done it right and if I haven't can you please suggest on how I can improve it? Any help is greatly appreciated and thank you in advance!

Answer

correct table is

num1    num2    i       output
0       0       0       0
1       1       1       1
4       5       2       4
9       14      3       9
16      30      4       16
                5       30