Results 1 to 3 of 3
  1. #1
    Join Date
    May 2013
    Posts
    2
    Rep Power
    0

    Default 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);
    }
    }

  2. #2
    monkeyjr97 is offline Senior Member
    Join Date
    Nov 2012
    Posts
    258
    Rep Power
    3

    Default 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.

  3. #3
    Join Date
    May 2013
    Posts
    2
    Rep Power
    0

Similar Threads

  1. Exam Question
    By joepeger in forum New To Java
    Replies: 17
    Last Post: 01-28-2013, 08:14 PM
  2. help me with a practice test question ? there is no answer
    By stephanie904 in forum New To Java
    Replies: 2
    Last Post: 02-28-2012, 02:20 AM
  3. Java exam question help
    By eoins2345 in forum New To Java
    Replies: 7
    Last Post: 08-20-2011, 08:04 PM
  4. Exam prep Question
    By tonto2010 in forum New To Java
    Replies: 4
    Last Post: 05-10-2011, 02:11 AM
  5. Exam Practice Questions
    By AWPtic in forum New To Java
    Replies: 24
    Last Post: 04-18-2009, 04:50 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •