Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

some predict output practice problem

so this is not from treehouse, its from other resource,

What is the output of this program?

class evaluate {
    public static void main(String args[]) 
    {
        int a[] = {1,2,3,4,5};
    int d[] = a;
    int sum = 0;
    for (int j = 0; j < 3; ++j)
            sum += (a[j] * d[j + 1]) + (a[j + 1] * d[j]);
    System.out.println(sum);
    } 
}

the answer is c 40, I dont get this,

int d[] = a , so d is exactly the same as a.

++j , j becomes 1, sum += (a[1]*d[2]) + (a[2]*d[1]) sum += (a[1]*a[2]) + (a[2]*a[1]) // sum = 12

j increment to 2 sum += (a[2]*a[3]) + (a[2]*a[3]) // sum = 12 + 24 =36

j increment to 3 sum += (a[3]*a[4]) + (a[3]*a[4]) // sum = 36 + 24 = 60

please point out where i did wrong thanks

2 Answers

j starts at 0. I think you skipped that. So really, it would be this: j=0: sum+= (a[0]d[1]) + (a[1]d[0]). 2+2 = 4. Continue with what you have already....... The only thing is j never reaches 3, because it only goes up while it's LESS THAN, not less than or equal to. So remove your last line. Then you get: 36+4 (from above) = 40

but ++j does increment before hand?

Nope. The way it works is it starts off at 0, goes through the process, and then once it reaches the end, that's when it increments and starts over.

so whats the difference between j++ and ++j? j = 0 j++ means next time it execute the function it increments while ++j means function will be executed as j = 0 and then j increments to 1 at this point?

There's no difference. It's just how they decided to type it. j++ and ++j will result in the exact same thing. (Go ahead and try switching it around! You'll see for yourself.)

Just to throw in my few cents to this conversation. The difference between post and pre increment is: Pre-increment(++num) increments the value first THEN it uses the variable. Post-increment (num++) uses the variable first, THEN it increments the value.

int num = 0;
System.out.println(num++);  //prints out 0

//now num is 1

System.out.println(++num);  //prints out 2

It wouldn't matter which one you use in a for-loop, they would both display the same output.