Print for java explanation

I am trying to understand the following Java exercise. Even starting the debugger, I don’t understand the details of the second and third listing:

1, 2, 3, 4

1, 2, 4, 4

1, 2, 4, 8

I understand that the first print is an array as it is, the second line prints the [2] element of the array and the third element [3]. 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();
    }
}
+6
source share
3 answers

See what this method does:

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

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

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

A call with v[2] - 1takes a value in the index 2(which 3) and subtracts 1, so we have y = 2.

, , 1 (y-1), 2, 2, 4 2 (y).

: {1,2,4,4}

v[3] - 1 3 ( 4) 1, y = 3.

, , 2 (y-1), 4, 2, 8 3 (y).

: {1,2,4,8}

+2

, . :

1 2 3 4

, .

:

x(v, v[2] -1 ) ... evaluates to

x(v, 3 - 1)    ... evaluates to

x(v, 2)

:

array[y] = array[y - 1] * 2;

y 2 (. ):

array[2] = array[1] * 2;

array[2] = 2 * 2;

:

1, 2, 4, 4

, : . , "".

+5

printalways prints the entire array. xand ymake changes to the array between them.

Keep in mind that v[x]is an integer. For example, v[2]starting is simple 3, therefore v[2] - 1 = 2. Therefore, it changes v[2]between the first and second calls to print.

+1
source

Source: https://habr.com/ru/post/1017271/


All Articles