Print array elements using recursion

Problem statement:- Program to print array elements 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 elements using recursion.

Code:

#include<stdio.h>
void PrintArray(int arr[], int i, int n)
{

    if(i>=n)
        return;
    printf("%d ",arr[i]);
    PrintArray(arr,i+1,n);
}
int main()
{
    int n,i;
    printf("Enter your array size:");
    scanf("%d",&n);
    int arr[n];
    printf("Enter the Array Element:");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    printf("Array Element Are:");
    PrintArray(arr,0,n);
}

Input/Output:
Enter your array size:5
Enter the Array Element:4 8 10 3 5
Array Element Are:4 8 10 3 5

Program in C++

Here is the source code of the C++ Program to print array elements using recursion.

Code:

#include<iostream>
using namespace std;
void PrintArray(int arr[], int i, int n)
{

    if(i>=n)
        return;
    cout<<arr[i]<<" ";
    PrintArray(arr,i+1,n);
}
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<<"Array Element Are:";
    PrintArray(arr,0,n);
}

Input/Output:
Enter your array size:6
Enter the Array Element:9 13 55 65 100 2
Array Element Are:9 13 55 65 100 2

Program in Java

Here is the source code of the Java Program to print array elements using recursion.

Code:

import java.util.Scanner;
public class PrintArrayElement {
static void PrintArray(int arr[], int i, int n)
{
if(i>=n)
return;
System.out.print(arr[i]+" ");
PrintArray(arr,i+1,n);
}
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("Array Element Are:");
PrintArray(arr,0,n);
cs.close();

}
}

Input/Output:
Enter your Array Size:
9
Enter the Array Element:
7 3 5 6 500 6 9 2 1
Array Element Are:7 3 5 6 500 6 9 2 1 

Program in Python

Here is the source code of the Python program to print array elements using recursion.

Code:

def PrintArray(arr,i,n):
    if(i>=n):
        return
    print(arr[i],end=" ")
    PrintArray(arr,i+1,n)
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("Array Element Are:")
PrintArray(arr,0,n)

Input/Output:

Post a Comment

0 Comments