1

What I need to do is in the comments before the method. A holds a 10 element long array the user inputs:

//Reverses the contents of the array. The array remains unchanged
    //It prints the reversed array to the screen
    static void reverseArray(int [] A)
    {
        int[] tempArray = new int[10];

      for(int i = A.length-1; i >= 0; i--)
      {
        //Supposed to copy what's in reversed array A to tempArray
        tempArray[i] = A[i];
      }
        printArray(tempArray); //Prints the updated array to the screen
    }

What I wanted it to do was count backward from the last element of A to the first and then copy that to tempArray. But now it just prints the array the user inputted. I know that I need 2 integers to keep track of what's increasing and decreasing but I don't know how to implement them.

Tyler P
  • 137
  • 9

3 Answers3

1

First of all, don't hard code the length of tempArray. Use the length of A:

int[] tempArray = new int[A.length];

Second of all, copy each element of A to the inverse index of tempArray:

for(int i = A.length-1; i >= 0; i--) {
  tempArray[A.length-1-i] = A[i];
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

This is my approach

    static void reverseArray(int [] A){
        int[] tempArray = new int[A.length];
        for(int i = 0; i < A.length; i++){
             tempArray[i] = A[A.length - i - 1];
        }
        printArray(tempArray); //Prints the updated array to the screen
    }

    static void printArray(int[] array){
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
    }
ABC
  • 595
  • 2
  • 5
  • 20
0

So I saw this answer and it really helped. I could've also went with my original plan of using a for loop but a while loop works well too. The former is probably easier because I don't need to make more variables but it's okay.

static void reverseArray(int [] A)
    {
      int i = A.length - 1;
      int j = 0;
      int[] tempArray = new int[A.length];

      while(i >= 0)
      {
        tempArray[j] = A[i];
        i--;
        j++;
      }
        printArray(tempArray); //Prints the updated array to the screen
    }
Tyler P
  • 137
  • 9