0
Here is the code to reverse an array

import java.util.*;
class middle {
    public static void main(String args[]){
        int a[]=new int[]{2,3,65,4,7,8,9};
        int c[]=new int[a.length-1];
        int k=0;
        for(int i=a.length;i>0;i++){
            c[k]=a[i];
            k++;
        }

        System.out.println("Reverse of an array");
        for(int i=0;i<c.length;i++)
            System.out.print(c[i]+"   ");
    }
}

while running gives Array index out of bound exception:7 where the code is going wrong?

2
  • 1
    array[array.length] will always be out of bounds. Array indices go from 0 to length-1. See also the official tutorial on arrays. Commented Apr 12, 2014 at 16:38
  • 1
    Please please PLEASE format your code. Also, please use Java naming conventions - classes should be in PascalCase; Middle not middle. Commented Apr 12, 2014 at 16:38

3 Answers 3

1

a.length is out of bound for a

for(int i=a.length;i>0;i++)
{
 c[k]=a[i];
 k++;
}

then,

int c[]=new int[a.length-1];

you need same length array for, not length - 1 for reverse array

Sign up to request clarification or add additional context in comments.

1 Comment

@Raju your comment doesn't support -1
1

To loop through the array backwards, you need to change all three conditions in your loop, like so:

for(int i=a.length-1;i>=0;i--)
{
 c[k]=a[i];
 k++;
}

Let's take this apart:

int i=a.length-1;

You must begin at a.length-1, as arrays use 0-based indexing and a.length is out of bounds.

i>=0;

You need to iterate until i>=0, as i>0 will miss one element of your array.

i--

You need to decrement i, as the loop will always access out of bounds indexes/never terminate otherwise.

P.S. As @Jigar mentioned, you need to initialize c as int c[]=new int[a.length];.

Comments

0

you did mistake here , you need to mention the length of array a.length not a.length-1 for c and the values in for loop conditions should have like for(int i=a.length-1;i>=0;i--) i should be decremented. : modified code is here:

int a[]=new int[]{2,3,65,4,7,8,9};
int c[]=new int[a.length];

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

c[k]=a[i];
k++;

}

1 Comment

This answer would be more useful if you pointed out the mistakes and explained why your modifications solve the issues. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.