C program to print elements of array using recursion

Write a C program to print all elements of array using recursion. How to display all elements of an array using recursion. Logic to print array elements using recursion in C programming.

Example

Input

Input size: 10
Input elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Output

Array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Required knowledge

Basic C programming, If else, Functions, Recursion, Array

Learn more – Program to read and display array elements using loop.

Logic to print array elements using recursion

Let us first define our recursive function to print array elements, say printArray(int arr[], int start, int len). The function takes three parameters where first is array to print, second is starting index from where we want to print array and last is length of the array or upper limit to print elements in array. Here

  • start >= len is used as base condition of recursion. Which will exit function control to the caller function.
  • If base condition is not satisfied then print arr[start].
  • After printing array element make recursive call to print successive array element i.e. printArray(arr, start + 1, len);.

Program to print array elements using recursion

/**
 * C program to print array elements using recursion.
 */

#include <stdio.h>
#define MAX_SIZE 100

/* Function declaration */
void printArray(int arr[], int start, int len);


int main()
{
    int arr[MAX_SIZE];
    int N, i;
    
    /* Input size and elements in array */
    printf("Enter size of the array: ");
    scanf("%d", &N);
    printf("Enter elements in the array: ");
    for(i=0; i<N; i++) 
    {
        scanf("%d", &arr[i]);
    }
        
    /* Prints array recursively */
    printf("Elements in the array: ");
    printArray(arr, 0, N);
    
    return 0;
}


/**
 * Prints an array recursively within a given range.
 */
void printArray(int arr[], int start, int len)
{
    /* Recursion base condition */
    if(start >= len)
        return;
        
    /* Prints the current array element */
    printf("%d, ", arr[start]);
    
    /* Recursively call printArray to print next element in the array */
    printArray(arr, start + 1, len); 
}

Output

Enter size of the array: 10
Enter elements in the array: 1 2 3 4 5 6 7 8 9 10
Elements in the array: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Happy coding 😉