Looping elements in an array back

Here is 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 would like to print the array in descending order, and not in ascending order (from the last element of the array to the first), but I just got this error:

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

Why is this happening? I was hoping that using myArray.length to set the counter to 8, the code simply prints the eighth element of the array and then saves it before that.

+12
java arrays for-loop
source share
7 answers

Arrays in Java are indexed from 0 to length - 1 , not from 1 to length , so you should 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--) { 
+59
source share
  • The first index is 0, and the last index is 7 not 8
  • Array size is 8
+4
source share

use myArray.length-1

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

The problem here is this piece of code: myArray.length . In Java, as in most other languages, data structures are based on 0, so the last element has an index structure.length - 1 (and the first is 0 ). Therefore, in your case, you should change your loop as follows:

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

You start with the wrong index. Do it like this:

 for(int counter= myArray.length - 1; counter >= 0;counter--) { 

The last index of the array is its length minus 1.

+2
source share

the counter starts with the index myArray.length, which actually counts from 1 instead of 0 ..

  for(int counter=myArray.length - 1; counter > 0; counter--){ 
+2
source share

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

Here, the specified length of the array is 8, since the count starts from 1, but for the index myArray[0] = 1; and so on .... here the number of indices starts at 0. So, in your code snippet

 for(int counter = myArray.length - 1; counter >= 0; counter--) { 

comes out of the bounds of the array, so it shows you an ArrayIndexOutOfBoundsException .

0
source share

All Articles