Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through the elements in an array backwards [duplicate]

Tags:

Here's my code:

int myArray[]={1,2,3,4,5,6,7,8};

for(int counter=myArray.length; counter > 0;counter--){
    System.out.println(myArray[counter]);
}

I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
    at task1.main(task1.java:14)

Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.

like image 395
JimmyK Avatar asked Feb 21 '12 14:02

JimmyK


People also ask

How do I print an array in reverse order?

To print an array in reverse order, we shall know the length of the array in advance. Then we can start an iteration from length value of array to zero and in each iteration we can print value of array index. This array index should be derived directly from iteration itself.

Does Reverse change the original array?

// Careful: reverse is destructive -- it changes the original array.


2 Answers

Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.

Your loop should look like this:

for (int counter = myArray.length - 1; counter >= 0; counter--) {
like image 91
Tim Cooper Avatar answered Oct 22 '22 04:10

Tim Cooper


  • The first index is 0 and the last index is 7 not 8
  • The size of the array is 8
like image 21
VirtualTroll Avatar answered Oct 22 '22 03:10

VirtualTroll