Reputation: 1
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
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
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
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