Reverse an array

 Take as input N, a number. Take N more inputs and store that in an array. Write a recursive function which reverses the array. Print the values of reversed array.

Input Format

Enter a number N and take N more inputs

Constraints

None

Output Format

Display values of the reversed array

Sample Input
4
1
2
3
4
Sample Output
 4 3 2 1

Solution :
import java.util.*;
public class ReverseArray {
public static void main(String args[])
{
 Scanner s=new Scanner(System.in);
 int length=s.nextInt();
 int arr[]=new int[length];
 for(int i=0; i<arr.length; i++)
 {
 arr[i]=s.nextInt();

 }
       
 s.close();
 reverseArray(arr,0);
 System.out.println(Arrays.toString(arr));
 }
 private static void reverseArray(int arr[],int i)
 {
 if(i>=arr.length/2)
 {
  return;
 }
  int temp;
 temp=arr[i];
 arr[i]=arr[arr.length-i-1];
 arr[arr.length-i-1]=temp;
 reverseArray(arr, i+1);
 }
   
}

4 3 2 1

Post a Comment

0 Comments