Store values in an inverted order vector

1

The goal is to read 10 values of a given vector, and then create another vector that has the same values as the first vector, but in inverted order, for example, the first value of the 1st vector is the tenth of the 2nd vector, the second value of the 1st vector is the penultimate of the 2nd vector, and so on. I tried to do however the second vector always has a value of 0. I know I have to use for for this, but I do not know if I used it correctly.

public static void main(String[] args) {

    int [] firstArray = new int [10];
    int [] secondArray = new int [10];

    for (int i = 0; i < firstArray.length; i++) {
        firstArray[i] =(int)Math.round(Math.random()*50); //Gerando valores aleatórios
    }

    //Passando valores
    for (int i = 9; i <= 0; i--) {
        for (int j = 0; j < secondArray.length; j++) {
            secondArray[j] = firstArray[i];
            break;
        }
    }

    //Apresentar valores
    System.out.println("\nPrimeiro Array:");
    for (int i = 0; i < firstArray.length; i++) {
        System.out.print(firstArray[i]+"; ");
    }

    System.out.println("\nSegundo Array:");
    for (int i = 0; i < secondArray.length; i++) {
        System.out.print(secondArray[i]+"; ");
    }
    System.out.println("");
}
    
asked by anonymous 26.05.2016 / 20:43

1 answer

2

As you will only touch an array , you only need a loop. To find the element of the other array just use math. Just calculate the index in reverse. You could scan the array from the first to the last one the formula works the same. The inversion formula of the elements is universal. In addition there was a wrong signal on the first loop preventing it from running. The correct would be:

for (int i = firstArray.length - 1; i >= 0; i--) {
    secondArray[secondArray.length - i - 1] = firstArray[i];
}

See working on ideone and CodingGround .

Ideally it should have a constant with the size of array to be used in both, so it would ensure that both have the same size. It does not affect the code at all, but it gives more semantics to what you want. The way it is, if someone fiddles with the code, you may not want to create problems.

If there was a need for two loops, it could not be the way it used, break was closing the loop in the first pass, so the loop did not actually occur.

    
26.05.2016 / 21:21