1
static int[] fun1(int[] ar){

        int[] auxarray = new int[ar.length];
        int j = ar.length;
        for (int i = 0; i < ar.length; i++) {

            auxarray[j - 1] = ar[i];
            j = j - 1;

        }

            return ar;

    
}

I have tried to implement a swap method to modify the same array, but it didn't work (tested with a void method and printed the result inside it: same as the initial array)

public static void main(String args[]){

        Scanner input = new Scanner(System.in);

        System.out.print("Please enter the size of the array: ");
        size = input.nextInt();
        array = new int[size];   //array and size are declared private static globally

        for(int i = 0; i<size; i++){
            array[i] = input.nextInt();
        }

        System.out.println("Your reversed string is:");
        int[] reversedarray = fun1(array);
        for(int i = 0; i < size; i++){
        System.out.print(reversedarray[i] + ' ');
        }
    }

This returns 3334353637.. in all cases. Any solution or any idea on what I have done wrong?

VicVerevita
  • 37
  • 1
  • 1
  • 6
  • you got your answer below. if you had chosen some more convenient names than `ar` and `auxarray`, e.g. `original` and `reversed` it may have been more obvious. – Curiosa Globunznik Nov 08 '20 at 14:16
  • in `fun1` change the return array from `return ar` to `return auxarray`; – Mustafa Poya Nov 08 '20 at 14:47
  • So I got it all sorted out. Other than the fact that I have mistaken the array (this was a thing I missed when I tried to debug, because I have tried ~6 different methods), when I try to print the array I used ' ' instead of " ", which was returning the unwanted "3". – VicVerevita Nov 09 '20 at 17:29

3 Answers3

0

You are returning the wrong array,ar instead of auxarray

Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24
dssjoblom
  • 124
  • 1
  • 4
0

error is in your fun1

  • You are returning a wrong array

What you can consider as an enhancement

You can simply swap the elements in the same array only iterate half the length of the array

static int[] fun1(int[] ar){
    int size = ar.length, temp;
    for (int i = 0; i < size/2; i++) {
        temp = ar[i];
        ar[i] = ar[size-1-i];
        ar[size-1-i] = temp;
    }

    return ar;
}
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
0

Return auxarray instead of ar.

iamanbansal
  • 2,412
  • 2
  • 12
  • 20