Reverse an Array in Java using Recursion

In this java program tutorial, we will write a java program to reverse an array using recursion. Before that, you may go through the following topic in java.

Explanation: In this java program we will take user input for the size of an array and array elements. The elements are reversed using a recursive function in the program below.


Reverse an Array in Java using Recursion

import java.util.Scanner;

public class Main
{
  public static void main(String args[])
  {
    int size, i;
    int arr[] = new int[50];
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter the size of a first array: ");
    size = scan.nextInt();

    System.out.println("Enter " + size + " elements in first Array:");
    for (i = 0; i < size; i++)
      arr[i] = scan.nextInt();

    System.out.print("Original array: ");
    for (i = 0; i < size; i++)
      System.out.print(arr[i] + " ");

    //calling a function
    reverseFunc(arr, 0, size - 1);

    System.out.print("\nReversed array: ");
    for (i = 0; i < size; i++)
      System.out.print(arr[i] + " ");
  }

  static void reverseFunc(int arr[], int start, int end)
  {
    int temp;
    if (start >= end)	//base condition
      return;

    temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    reverseFunc(arr, start + 1, end - 1);
  }
}

Enter the size of a first array: 5
Enter 5 elements in first Array:
1
2
3
4
5
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1