Home » Java » java – I am getting an error when reversing an array by iterating it till half-Exceptionshub

java – I am getting an error when reversing an array by iterating it till half-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have tried to reverse an array by running it till half so that if it has odd number of element then middle one is left out as it is not needed to be swapped and if it’s even then every element will be swapped but I don’t know where I’m wrong.

import java.io.*;
import java.util.*;

public class Main{

    public static void main(String[] args) throws Exception {
        // write your code here
        Scanner scn = new Scanner(System.in);
        int x = scn.nextInt();
        int[] arr = new int[x];
        for(int i = 0 ; i < arr.length ; i++)
        {
            arr[i] = scn.nextInt();
        }
        int temp = x;
        for(int i = 0  ; i < temp / 2 ;i++)
        {
            int temp1 = arr[i];
            arr[i] = arr[x - 1];
            arr[x - 1] = temp1;
            x--;
        }
        for(int z=0;z<arr.length;z++)
        {
            System.out.println(arr[z]);
        }
    }
}
How to&Answers:

You were very close in your attempt. See the following with changes.

       for(int i = 0  ; i < temp / 2 ;i++)
        {
            int temp1 = arr[i];
            arr[i] = arr[x - 1]; // should be arr[x - i - 1]
            arr[x - 1] = temp1;  // should be arr[x - i - 1]
            x--; // delete this line
        }