0

I would want to assign the array elements reversely into another array using this code. I need help.

int a[] = {1, 2, 3, 4, 5};
int aR[] = new int[a.length];
for (int i=0; i <= a.length; i++) {
    for (int j=aR.length; j >= aR.length; j--) {
        aR[j] = a[i];
    }
}
System.out.println(Arrays.toString(aR));

I expect the output to be [5, 4, 3, 2, 1], but the output is an Array Exception.

  • 1
    why do you need a second loop? you only need one – Stultuske Aug 21 '19 at 08:51
  • You just need one for loop and not two, run the for loop from i = (a.length-1) to 0 and decrement the counter – Tarun Gupta Aug 21 '19 at 08:52
  • The problem is in your inner loop, those conditions doesn't make any sense whatsoever. You start from `j=0` and decrement the value as long as it is greater or equal `aR.length`. You probably wanted to start from `aR.length` till its equal 0. – Amongalen Aug 21 '19 at 08:52
  • 1
    Second note: `int i=0; i <= a.length; i++` is incorrect, you want to iterate till `i` is lower than `a.legth`, not lower or equal. – Amongalen Aug 21 '19 at 08:53
  • As mentioned in the comments you only need one single loop. `j = arr.length; for (int i = 0; i < arr.length; i++) {aR[j - 1] = a[i];j = j - 1;}` – SSharma Aug 21 '19 at 09:00
  • You could try using following code `for (int i = 0; i < a.length; i++){ b[i] = a[(a.length - 1) - i]; }` – Digvijaysinh Gohil Aug 21 '19 at 09:00
  • If you iterate an array in reverse, you shouldn't start with `length` but with `length - 1` , and do it while `j >= 0` – bvdb Aug 21 '19 at 09:06

2 Answers2

3

You can do that in many different ways, as you tried, just get and assign the element by reverse order, like below:

int[] a = {1, 2, 3, 4, 5};
    int[] aR = new int[a.length];
    int index = 0;
    for (int i=a.length-1; i >=0; i--) {
            aR[index] = a[i];
            index++;
    }
    System.out.println(Arrays.toString(aR));
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Amit
  • 1,540
  • 1
  • 15
  • 28
  • 1
    I run this code and the result is: [5, 4, 3, 2, 1], because I just overwritten the element so, It's obvious. :) – Amit Aug 21 '19 at 09:03
  • 1
    that "`index`"-thing is unneeded. Just do a `for (int i=0; i< a.length; i++) { aR[a.length-1-i] = a[i]; }` and you're done... – SirFartALot Aug 21 '19 at 09:13
  • 1
    Correct, I probably should have finished my coffee before commenting ;-) – GhostCat Aug 21 '19 at 09:20
0

Code modified to :

int a[] = {1, 2, 3, 4, 5};
int aR[] = new int[a.length];
for (int i=0; i < a.length; i++) {
    int j = (a.length-1) - i;
    aR[j] = a[i];
}
System.out.println(Arrays.toString(aR));

You got an Exception cause if the length of an array is n then the final valid index is n-1
Length 1,2,3,4 ...
But Index 0,1,2,3 ....
So, always 1 less than that of length.