Tatention
Tatention

Reputation: 7

Why won't this print in Reverse?

I have a very simple problem but I can't seem to solve it. I'm getting an out of bounds error on this code

int c = 0;
System.out.println();
System.out.println("Printing array in Reverse order:");
for (int i = array.length ; i >= -1; i--)
{
   System.out.println(array[i] +" ");
   c++;
   if(c == 10) 
   {
       System.out.println();
       c=0;
   }
}

What's the deal?

Upvotes: 0

Views: 73

Answers (4)

coldy
coldy

Reputation: 2195

Here is a small piece of code which will work you to get the reverse :)

public class newarray {

    public static void main(String args[]){

        int arr[]={10,20,30};
        int size=arr.length;
        for(int i=size-1;i>=0;i--){
            System.out.println(arr[i]);


        }


    }
}

OutPut :

30 20 10

Upvotes: 0

angel_navarro
angel_navarro

Reputation: 1777

In Java, array index go from 0 to "length - 1". So if you start in array.length, you are trying to access out of the array's positions. Same occurs if you try to access to -1 index, because your least index is 0.

Upvotes: 0

Tommy
Tommy

Reputation: 1985

for (int i = array.length ; i >= -1; i--) {

wrong, arrays starts at index zero, so a "length" array is from index 0 to index "length - 1"

so your code is wrong, you should use

for (int i = array.length - 1 ; i >= 0; i--) {

Upvotes: 3

rpax
rpax

Reputation: 4496

You get an IndexOutOfBounds because you're starting out of the array

int c = 0;
    System.out.println();
    System.out.println("Printing array in Reverse order:");
    for (int i = array.length -1; //HERE
                          i >= 0;//HERE
                          i--) {
      System.out.println(array[i] +" ");
      c++;
      if(c == 10) {
       System.out.println();
       c=0;
      }
    }

Upvotes: 0

Related Questions