Please explain to me what I am doing wrong?

Hello!

I am preparing for my exam. And I am doing some java exercises from the book. But here I have some problem. My answer does not match with the book's answer. Please explain what I am doing wrong.

here is the code:

public class EX5 {

public static void main (String [ ] args) {

int [ ] data = {6, 2, 5, 1, 10, 3, -3};

int result = 0;

for (int i = 2; i < data.length; i++) {

result = result + (data[i] - data[i-2]);

System.out.println("result = " + result);

}

}

}

the book answer is

result = -1

result = -2

result = 3

result = 5

result = -8

.

But my answer is :

-1

-1

5

2

-13

Best regards

Re: Please explain to me what I am doing wrong?

When posting code, please use the highlight tags to preserve formatting.

I copied that code and got the same as the book. Are you sure you're recompiling and running the correct class file?

Re: Please explain to me what I am doing wrong?

Ok next time i'll post codes' as yo suggested.

Well, the book says that I have to give answer by myself without using computer.

I calculated by myself.

First I thought that " i " starts from 2. so result + data[2] - data [2-2]= 0+ 5 - 6 = -1

then i increasing by 1, right (i++)

result + data [3] - data [3-2]= 0 + 1 - 2 = -1

result + data [4] - data [4-2]= 0 + 10 - 5 = 5 and so on.

which is obviously wrong answer. I want to know what i am doing wrong though

Re: Please explain to me what I am doing wrong?

Ah, I see, you're trying to run through the code in your head.

Result does not rest to 0 each time through the loop. I recommend stepping through this with a debugger if you aren't sure what's going on.