print out for java exercise explanation

matrix :

I'm trying to understand the following Java exercise. Even running the debugger I don't understand the details of the second and third printout:

1, 2, 3, 4

1, 2, 4, 4

1, 2, 4, 8

I understand that the first print is the array as it is, second line prints [2] element of the array and third line [3] element. Here is the code:

public class TR1
{
    public static void main(String[] args)
    {
        int[] v =  {1, 2, 3, 4 };
        print(v);
        x(v, v[2] - 1);
        print(v);
        x(v, v[3] - 1);
        print(v);
    }

    public static void x(int array[], int y)
    {
        array[y] = array[y - 1] * 2;
    }

    public static void print(int array[])
    {
        System.out.print(array[0]);
        for (int i = 1; i < array.length; i++)
            System.out.print(", " + array[i]);
        System.out.println();
    }
}
Arnaud :

Let's see what this method does :

public static void x(int array[], int y)
    {
        array[y] = array[y - 1] * 2;
    }

It takes the value at index y-1, multiplies it by 2, then assigns this result to the index y .

Starting array : {1,2,3,4}

The call with v[2] - 1 takes the value at index 2 (which is 3), and substracts 1, so we have y = 2.

From what we said before, the method takes the value at index 1 (y-1) which is 2, multiplies it by 2 so we get 4, and assigns that to the index 2 (y) .

Current array : {1,2,4,4}

The call with v[3] - 1 takes the value at index 3 (which is 4), and substracts 1, so we have y = 3.

From what we said before, the method takes the value at index 2 (y-1) which is 4, multiplies it by 2 so we get 8, and assigns that to the index 3 (y) .

Current array : {1,2,4,8}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466045&siteId=1