-4

Here is my code to reverse the elements in an array:

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] arr = new int[n];
        for(int i=0; i < n; i++){
            arr[i] = in.nextInt(); 
        }
        int i=0;
        int j=n-1;
        int c;
        while(i<j){
            c=arr[i];
            arr[i]=arr[j];
            arr[j]=c;
            i++;
            j--;
        }
        System.out.println(arr[n]);
        in.close();
    }
}

The problem is my code is generating arrayIndexOutOfBound exception. How to remove it ?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Abhi
  • 5
  • 2

3 Answers3

1

Change,

System.out.println(arr[n]);

to:

System.out.println(Arrays.toString(arr));
Ekaba Bisong
  • 2,918
  • 2
  • 23
  • 38
1

System.out.println(arr[n]); Here is the problem because there's no index "n" n is the number of elements You have to loop form 0 to n-1

    for(int i =0;i < n;i++){
System.out.println(arr[i]);

}
Renuka Deshmukh
  • 998
  • 9
  • 16
0

your code works fine for reversing the array of elements but arrayIndexOutOfBound exception is raised due to System.out.println(arr[n]). Remember array index starts from zero.For n size array, the range will be [0,(n-1)] ie., if n=5 range will be 0 to 4.

for(int k=0;k<arr.length;k++)
{ 
   System.out.println(arr[k]);
}
Likhith Kumar
  • 161
  • 4
  • 9