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.

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

Required knowledge

Basic C programming, Functions, Recursion

Logic to print array elements using recursion

We have already seen many programs on array and also how to read and display array elements using loops. Here we need to define logic to print array elements using recursion. For this we will be defining a recursive function named printArray(int arr[], int start, int len). Mentioned 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.
But for a successful recursive function we need a base condition of recursion, hence I have used below statement as my base condition to print array elements:
if(start >= len) return;

Program to print array elements

/**
 * 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;
    
    /*
     * Reads 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)
{
    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 ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment