reverse for loop for array countdown

107,369

Solution 1

Java uses 0-based array indexes. When you create an Array of size 10 new int[10] it creates 10 integer 'cells' in the array. The indexes are: 0, 1, 2, ...., 8, 9.

Your loop counts to the index which is 1 less than 11, or 10, and that index does not exist.

Solution 2

You declared array on integers of 10 elements. And you are iterating from i=0 to i=10 and i=10 to i=0 that's 11 elements. Obviously it's an index out of bounds error.

Change your code to this

public class Reverse {

  public static void main(String [] args){
    int i, j;

    System.out.print("Countdown\n");

    int[] numIndex = new int[10]; // array with 10 elements.

    for (i = 0; i<10 ; i++) {  // from 0 to 9
      numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
    }

    for (j=9; j>=0; j--){ // from 9 to 0
      System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?   
    } 

  }
}

Remember indices starts from 0.

.

Solution 3

The array is of size 10, which means it is indexable from 0 to 9. numIndex[10] is indeed out of bounds. This is a basic off-by-one error.

Solution 4

An Array in java that has 10 elements goes from 0 to 9. So your loops need to cover this range. Currently you are going from 0 to 10, and 10 to 0.

Share:
107,369
KamikazeStyle
Author by

KamikazeStyle

Updated on March 22, 2020

Comments

  • KamikazeStyle
    KamikazeStyle about 4 years

    I get the error..

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
        at Reverse.main(Reverse.java:20). 
    

    There is not wrong in the syntax so im not sure why when it compiles it gets an error?

    public class Reverse {
    
    public static void main(String [] args){
        int i, j;
    
    
        System.out.print("Countdown\n");
    
        int[] numIndex = new int[10]; // array with 10 elements.
    
        for (i = 0; i<11 ; i++) {
            numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
        }
    
        for (j=10; j>=0; j--){ // could have used i, doesn't matter.
            System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
        }
    }
    

    }