0

I have the code below:

int lines = 0;
while(lines < 2)
{
    int[] oldarr = parr;

    for(int i = 0; i < arrsize; i++)
        System.out.print(" " + oldarr[i]);
    System.out.println();

    for(int i = 0; i < arrsize; i++)
    {
        if(i == 0)
            parr[i] = 0;
        else
            parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
    }

    lines++;
}

parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..

Any ideas?

2
  • 2
    What are your numbers? Integer Overflow problems? Commented Apr 23, 2013 at 21:20
  • no no, just incorrect values. Say parr = "1, 2" the next iteration prints out "0, 4". Just not what [i] - [i-1] should be. Commented Apr 23, 2013 at 21:21

2 Answers 2

4

You aren't copying your array with this line:

int[] oldarr = parr;

The two variables are still pointing at the same array.

To get a copy, you can do:

int[] oldarr = Arrays.copyOf(parr, parr.length);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I knew it was something like this. I was about to do it manually with for loops. (sorry I just dont know enough java yet)
1

In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.

Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.

for(int i = arrsize - 1; i >= 0; i--)

1 Comment

oldarr hold the previous values, no data is destroyed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.