Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array Reverse logic

import java.util.Scanner;

public class Reverse {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arr[] = new int[5];
        System.out.println("Enter the values in the array");
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = sc.nextInt();
        }

        for (int i = 0; i < 5; i++) {
            int temp;
            int j = 4;
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            j--;
            System.out.println(arr[i]);
        }

    }
}

This logic is not reversing the array of integers why?????

input 123

output is 0123

like image 362
Aaditya Avatar asked Apr 29 '26 13:04

Aaditya


1 Answers

One approach you may try here is to simply swap each element in the array across the middle position:

int[] arr = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
for (int i=0; i < arr.length/2; i++) {
    int temp = arr[i];
    int j = arr.length - i - 1;
    arr[i] = arr[j];
    arr[j] = temp;
}
System.out.println(Arrays.toString(arr));

This prints:

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

The problem with your current logic is largely this line:

int j = 4;

You assign the upper pointer to the array as 4, for each iteration of the loop. Instead, the value j should be initialized as 4 outside of the loop, and then decremented during each iteration. But, I would probably use the version I gave above.

like image 75
Tim Biegeleisen Avatar answered May 01 '26 01:05

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!