Results 1 to 3 of 3
Thread: Practice Exam Question
 05102013, 02:51 AM #1Member
 Join Date
 May 2013
 Posts
 2
 Rep Power
 0
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);
}
}
 05102013, 03:05 AM #2Senior Member
 Join Date
 Nov 2012
 Posts
 258
 Rep Power
 2
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.
 05102013, 03:15 AM #3Member
 Join Date
 May 2013
 Posts
 2
 Rep Power
 0
Similar Threads

Exam Question
By joepeger in forum New To JavaReplies: 17Last Post: 01282013, 07:14 PM 
help me with a practice test question ? there is no answer
By stephanie904 in forum New To JavaReplies: 2Last Post: 02282012, 01:20 AM 
Java exam question help
By eoins2345 in forum New To JavaReplies: 7Last Post: 08202011, 07:04 PM 
Exam prep Question
By tonto2010 in forum New To JavaReplies: 4Last Post: 05102011, 01:11 AM 
Exam Practice Questions
By AWPtic in forum New To JavaReplies: 24Last Post: 04182009, 03:50 PM
Bookmarks