JimmyK JimmyK - 1 year ago 94
Java Question

Looping through the elements in a array backwards

Here's my code:

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

for(int counter=myArray.length; counter > 0;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.

Answer Source

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--){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download