Invert values from one vector to another vector

2

I am in the second semester of college, we are learning vector, and I am very lost in the list of exercises.

An exercise asks the user to type 5 elements for a vector, and then I have to get these elements, send them to another vector, only with inverted order. How can I do this?

Example:

vetor_original [ 1, 2, 3, 4, 5]
vetor_cppia [ 5, 4, 3, 2, 1]
    
asked by anonymous 18.02.2017 / 13:01

2 answers

1

You can do this:

int[] vetor_original = { 1, 2, 3, 4, 5 };
int tamanhoVetorOriginal = vetor_original.length;
int[] vetor_copia = new int[tamanhoVetorOriginal];
int tamanhoVetorOriginalZeroBased = tamanhoVetorOriginal - 1;
for(int i = 0; i < tamanhoVetorOriginal; i++) {
    vetor_copia[i] = vetor_original[tamanhoVetorOriginalZeroBased - i];
    System.out.print(vetor_copia[i]);
}

Output : 54321

Explanation

  • int tamanhoVetorOriginal : represents the size of the original vector. That is, 5 ;
  • int[] vetor_copia = new int[tamanhoVetorOriginal] : creates a new array / array with the same size as vetor_original ;
  • int tamanhoVetorOriginalZeroBased : arrays are zero-based structures. This means that your record count never starts from number 1, but from zero. Ex: if you do System.out.println(vetor_original[1]) it will print 2 instead of 1 , because the 1 register is in the vetor_original[0] position. I created this variable to use as a little trick to go through the array. If the size of vetor_original is 5 , if we go from 0 to 5 we will have 6 positions: 0, 1, 2, 3, 4, 5 . So I subtracted 1 from the original size, causing this variable to have the value 4 and when we go we will have: 0, 1, 2, 3, 4 - > 5 positions;
  • vetor_copia[i] = vetor_original[tamanhoVetorOriginalZeroBased - i] : iterates vetor_original backwards. Ex: assuming i = 0 , we will have: vetor_copia[0] = vetor_original[tamanhoVetorOriginalZeroBased - 0] - > in position 0 of vetor_copia is assigned the value of the last position of vetor_original ;
20.02.2017 / 14:22
0

You fall into a situation where you may not know what numbers are typed so you can do so automatically:

public static void main(String[] args) {
        int[] a = { 2, 3, 4, 5 };

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
        System.out.println("Agora a ordem invertida");
        for (int j = a.length - 1; j >= 0; j--) {
            System.out.println(a[j]);
        }

    }

First I make a for to print the original values and soon after I create another to show in an inverted way.

    
18.02.2017 / 13:42