Doubt about displaying inverted array

Asked

Viewed 737 times

2

Could you explain to me how it works to return an array with inverted values? I took this exercise to do, but I couldn’t. Then a colleague gave me this exercise to dissect him, but I didn’t understand anything :S.

package pct;
import java.util.Scanner;
public class Exer5 {
    public static void main(String[] args) {
        Scanner teclado = new Scanner (System.in);
        int[] vetor1 = new int[5];
        int tamanho =  vetor1.length;
        int[] vetor2 = new int[tamanho];

        for (int i = 0; i < 5; i++) {
            System.out.println("Digite um número:");
            vetor1[i] =  teclado.nextInt();

        }
        for (int i = 0; i < vetor1.length; i++) {
            tamanho--;
            vetor2[i] = vetor1[tamanho];
        }

        System.out.println("Os valores invertidos, foram:" +vetor2);
    }
}

My biggest doubts are in the second for, I hardly understood anything that happened there.

2 answers

1

In the second loop of repetition has a variable with name tamanho in which it receives the size of vetor1. In this way:

int tamanho =  vetor1.length;

That means right now tamanho = 5 for vetor1 has 5 positions. Each time you pass by for, this size is being decremented with tamanho--; which is equivalent to tamanho = tamanho - 1;

Therefore, when allocating vetor1[tamanho] at the vetor2[i], it will be reversing the order of the initial vector, taking the last position and inserting in the first. See what happens in the loop:

vetor2[0] = vetor1[4];
vetor2[1] = vetor1[3];
vetor2[2] = vetor1[2];
vetor2[3] = vetor1[1];
vetor2[4] = vetor1[0];

1


Explaining the code:

// Nome do pacote.
package pct;

// Essa classe serve para ler dados a partir de uma entrada.
import java.util.Scanner;

// Todo o código está dentro de uma classe.
public class Exer5 {

    // Dentro do método main, que é o método principal da aplicação (e o único neste caso).
    public static void main(String[] args) {

        // Cria um Scanner que lê entradas da entrada padrão (System.in).
        // "teclado" não é a melhor definição disso, mas de qualquer forma,
        // trata-se de um objeto que vai fornecer o que o usuário digitar.
        Scanner teclado = new Scanner (System.in);

        // Cria um array com 5 posições.
        int[] vetor1 = new int[5];

        // Seria mais fácil fazer assim: int tamanho = 5;
        int tamanho =  vetor1.length;

        // Outro array com 5 posições.
        int[] vetor2 = new int[tamanho];

        // Executa 5 vezes, contando (com i): 0, 1, 2, 3 e 4.
        for (int i = 0; i < 5; i++) {
            // Pede para o usuário digitar algo.
            System.out.println("Digite um número:");

            // Lê o que ele digitou e põe no array.
            vetor1[i] =  teclado.nextInt();

        }

        // Neste ponto o array1 vai estar preenchido com os 5 valores digitados.

        // Executa 5 vezes, contando (com i): 0, 1, 2, 3 e 4.
        for (int i = 0; i < vetor1.length; i++) {

            // A variável tamanho começa com 5.
            // Quando i for 0, tamanho será 4.
            // Quando i for 1, tamanho será 3.
            // ...
            // Quando i for 4, tamanho será 0.
            // Observe que tamanho sempre será a "posição reversa" no array.
            tamanho--;

            // Coloca o elemento de um array na posição reversa do outro.
            vetor2[i] = vetor1[tamanho];
        }

        // Deveria mostrar os valores invertidos. Mas vai dar errado!
        System.out.println("Os valores invertidos, foram:" +vetor2);
    }
}

The exit at the end will be something like this:

Os valores invertidos, foram:[I@1540e19d

Let’s improve this program:

package pct;

import java.util.Arrays;
import java.util.Scanner;

public class Exercicio5 {

    public static void main(String[] args) {
        int tamanhoVetor = 5;
        Scanner scan = new Scanner(System.in);
        int[] original = new int[tamanhoVetor];
        int[] inverso = new int[tamanhoVetor];

        for (int i = 0; i < tamanhoVetor; i++) {
            System.out.println("Digite um número:");
            original[i] = scan.nextInt();
        }

        for (int i = 0; i < tamanhoVetor; i++) {
            inverso[i] = original[tamanhoVetor - 1 - i];
        }

        System.out.println("Os valores invertidos foram " + Arrays.toString(inverso));
    }
}

The difference here is that I renamed some variables and instead of counting the variable tamanho back to front, I use this formula:

inverso[i] = original[tamanhoVetor - 1 - i];

Now, the first and last position of these two vectors are 0 and tamanhoVetor - 1. Therefore, the position of tamanhoVetor - 1 - i will be the last time i for 0, the penultimate when i for 1, the antepenultimate when i for 2, etc..

Arrays do not have the method toString() written, and therefore in System.out.println, the result is unintelligible and meaningless text. Using Arrays.toString(inverso), this problem is solved.

Finally, I define the size in only one place not to have tamanho and 5 scattered in various places incoherently. Also, the size variable (which I called tamanhoVetor not to be confused with the existing one) it never changes so that things don’t get so confused.

See here working on ideone (pay attention in the field stdin there in the ideone and compare with the output).

  • I’ll be honest. I’m having a hard time understanding the reverse[i] = original[sizeVetor - 1 - i];

  • @So let’s calculate. We have to tamanhoVetor == 5. When i == 0, that gives inverso[0] = original[5 - 1 - 0];, that is to say, inverso[0] = original[4];. When i == 1, that gives inverso[1] = original[5 - 1 - 1];, that is to say, inverso[1] = original[3];. When i == 2, that gives inverso[2] = original[5 - 1 - 2];, that is to say, inverso[2] = original[3];... And so on and so forth.

  • @Hardysec You see that the position given by the formula is always the mirror of i. The reason for being the mirror is that the i is how many houses you advanced from the beginning (if i == 0, you are at the beginning). Soon, tamanhoVetor - 1 - i is how many houses you returned from the end (the position tamanhoVetor - 1 is the end). If the number of houses you advance from the beginning is the same number of houses as you return from the end, you have mirror positions.

  • Thank you very much. I could understand better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.