C program to print elements of array using recursion

Write a C program to print all elements of any array using recursion. C program to read elements in an array from user and display all its elements using recursion. How to display all elements of an array using recursion. Logic to print elements of array using recursion in C program.

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, Functions, Recursion

Program to read and display array elements using loops

Logic to print array elements using recursion

To print array elements using recursion, we need to define a recursive function, say printArray(int arr[], int start, int len). The function takes three parameters where the first is the array, second is starting index from where we want to print array and last is length of the array or we can also call it as upper limit to print elements in array. Here

  • start >= len is used as a base condition of the recursion. Which will exit/return function control to the caller function.
  • If the 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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>