Print array in reverse order using recursion

Problem statement:- Program to Print array in reverse order using recursion.

Data requirement:-

   Input Data:-n, arr

  Output Data:-arr

Program in C

Here is the source code of the C Program to Print array in reverse order using recursion.

Code:

#include<stdio.h>
void ReverseArray(int arr[], int n)
{
    int i;
    if(n>0)
    {
        i=n-1;
        printf("%d ",arr[i]);
        ReverseArray(arr,i);
    }
return;
}
int main()
{
    int n,j;
    printf("Enter your array size:");
    scanf("%d",&n);
    int arr[n];
    printf("Enter the Array Element:");
    for(j=0;j<n;j++)
    {
        scanf("%d",&arr[j]);
    }
    printf("After reversing Array Element Are:");
    ReverseArray(arr,n);
    return 0;
}

Input/Output:
Enter your array size:5
Enter the Array Element:4 6 9 10 11
After reversing Array Element Are:11 10 9 6 4

Program in C++

Here is the source code of the C++ Program to Print array in reverse order using recursion.

Code:

#include<iostream>
using namespace std;
void ReverseArray(int arr[], int n)
{
    int i;
    if(n>0)
    {
        i=n-1;
        cout<<arr[i]<<" ";
        ReverseArray(arr,i);
    }
return;
}
int main()
{
    int n,i;
    cout<<"Enter your array size:";
    cin>>n;
    int arr[n];
    cout<<"Enter the Array Element:";
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    cout<<"After reversing Array Element Are:";
    ReverseArray(arr,n);
    return 0;
}

Input/Output:
Enter your array size:6
Enter the Array Element:7 3 5 9 14 41
After reversing Array Element Are:41 14 9 5 3 7

Program in Java

Here is the source code of the Java Program to Print array in reverse order using recursion.

Code:

import java.util.Scanner;
public class PrintArrayReverseOrder {
static void ReverseArray(int arr[], int n)
{
int i;
    if(n>0)
    {
    i=n-1;
    System.out.print(arr[i]+" ");
    ReverseArray(arr,i);
    }
}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int n,i;
System.out.println("Enter your Array Size:");
n=cs.nextInt();
int arr[]=new int[n];
System.out.println("Enter the Array Element:");
for(i=0;i<n;i++)
{
arr[i]=cs.nextInt();
}
System.out.print("After reversing Array Element Are:");
ReverseArray(arr,n);
cs.close();
}
}

Input/Output:
Enter your Array Size:
4
Enter the Array Element:
13 5 7 19
After reversing Array Element Are:19 7 5 13 

Program in Python

Here is the source code of the Python program to Print array in reverse order using recursion.

Code:

def ReverseArray(arr,n):
    if(n>0):
        i=n-1
        print(arr[i], end=" ")
        ReverseArray(arr, i)

arr=[]
n = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,n):
    num = int(input())
    arr.append(num)

print("After reversing Array Element Are:")
ReverseArray(arr,n)

Input/Output:

Post a Comment

0 Comments