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.
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.
// Careful: reverse is destructive -- it changes the original array.
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--) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With