user3388552
user3388552

Reputation: 1

Array Index out of Bound exception in a program for reverse of an array

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?

Upvotes: 0

Views: 1104

Answers (3)

Azar
Azar

Reputation: 1106

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];.

Upvotes: 1

Raju Sharma
Raju Sharma

Reputation: 2516

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++;

}

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240948

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

Upvotes: 1

Related Questions