user2958370
user2958370

Reputation:

Java program for recursively reversing an array

I am supposed to be writing a program to reverse the numbers in an array recursively. I don't really know much code at this point. This is what I have so far.

This is the reverse method itself:

  public static void reverse(int[] array, int i, int j)
  {
    if (i < j)
    {
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
      reverse(array, ++i, --j);

I am not sure if this is even right. I then have the main method.

  public static void main(String[] args)
  {
   Scanner input = new Scanner(System.in);
   System.out.println("Enter size of the array");
   int n = input.nextInt();
   int[] array = new int[n];

   for (int i =0; i <array.length; i++)
   {
     System.out.println("Enter number to be inputed into array.");
     array[i] = input.nextInt();

   }
    System.out.println(array);
  }

It is not printing out right and prints numbers and letter in text where I think it should be the array.

Upvotes: 1

Views: 2008

Answers (1)

nhgrif
nhgrif

Reputation: 62052

Change System.out.println(array); to this:

System.out.println(Arrays.toString(array));

Then you can see whether or not your method is properly reversing. Currently, you're not printing the contents of the array, just the memory address where your array resides.

Upvotes: 2

Related Questions