Looping through the elements in an array backwards

110,171

Solution 1

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--) {

Solution 2

  • The first index is 0 and the last index is 7 not 8
  • The size of the array is 8

Solution 3

use myArray.length-1

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

Solution 4

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

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

Solution 5

the counter is starting at the index of myArray.length which is actually counted from 1 instead of 0..

    for(int counter=myArray.length - 1; counter > 0; counter--){
Share:
110,171
JimmyK
Author by

JimmyK

Updated on July 09, 2022

Comments

  • JimmyK
    JimmyK almost 2 years

    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.

  • JimmyK
    JimmyK about 12 years
    Thanks a lot this worked great
  • James111
    James111 over 8 years
    I had this but instead of taking away 1 from the counter I just left it as is. Nice work.
  • ChuckZHB
    ChuckZHB about 3 years
    If I don't care about the index, could we do it like this type for (int i : nums) this way but with backwards sequence.