Practice Exam Question

• 05-10-2013, 02:51 AM
DigitalWeapons
Practice Exam Question
We have been given a practice exam question. Could anybody explain what is going on here. The result when executed is 14.

public class Test1 {
public static void main(String[] args) {
int i,sum=0;
for (i=0;i<4;i++) // We cannot understand this statement.
sum=sum+i*i; // and this one?
System.out.println(sum);
}
}
• 05-10-2013, 03:05 AM
monkeyjr97
Re: Practice Exam Question
what it does is executed a loop:

for (i=0;i<4;i++)

i = 0; says that the int i starts off with the value of 0

then i < 4 so it will continue doing the loop whilst i is less than 4, so until i = 3

i++ increases the value of i by 1 every time the loop executes hence why you put i < 4

This loop will execute 4 times because:

initially i = 0, i++ will make i become 1, i++ again will make i 2, i++ again will make i become 3, i++ again will make i become 4, the loop with not execute its code now because i is no longer less than 4.

sum=sum+i*i;

This code performs a a simple calculation, sum starts of = 0 as defined by this line: int i,sum=0; then every time the loop executes (whilst i<4) the value of sum changes:

sum = sum+i*i = sum+(i*i)

so first of all sum = 0 and i = 0, so sum+i*i = 0+0*0 so sum = 0.

Then after the loop fires again, sum = 0 still, but i = 1 so sum = 0+1*1 = 1 so sum = 1.

Then after loop fires again, sum = 1, but i = 2 so sum = 1+2*2 so sum = 5

now sum = 5 i = 3, so sum = 5+3*3 = 5+(3*3) = 5+(9) = 14, so sum = 14.

Now i = 4, so code will not execute.

so as you can see, it does in fact print out 14.
• 05-10-2013, 03:15 AM
DigitalWeapons
Re: Practice Exam Question
Thankyou Buddy :)