In this article, we will write a C program to print the elements of an array using recursion. The program first takes the elements of the array from the user as input and then prints each element with the help of recursion.
Sample Example:
Input:
Enter the size of the array: 5
Enter the array elements: 10 20 30 40 50
Output:
The Array Elements are: 10 20 30 40 50
In programming, recursion is a technique where a function calls itself to solve a problem. It involves breaking down a problem into smaller, similar subproblems and solving them recursively until a base case is reached.
The base case can be any condition based on the problem you are solving which stops further calls to the function. There should be at least one base case in every recursive function.
As we want to print every element of the array, we have to create a recursive function, which prints the current element of the array and then moves to the next element by incrementing the index by 1.
This continues until we reach the last element of the array. As soon as the last element is reached, the base condition is matched and the function stops its further calls.
See implementation in the following program:
// C program to print Array elements using Recursion #include <stdio.h> // Recursive function to print the array elements void printArray(int arr[], int size, int index){ // Base case: when index reaches the end of the array if(index == size){ return; } // Print the current element printf("%d ", arr[index]); // Recursive call to print the next element printArray(arr, size, index + 1); } int main() { int arr[100], size; printf("Enter the size of the array: "); scanf("%d", &size); printf("Enter the array elements: "); for(int i = 0; i < size; i++){ scanf("%d", &arr[i]); } printf("The Array Elements are: "); // Call the recursive function to print array printArray(arr, size, 0); return 0; }
Output:
Enter the size of the array: 5 Enter the array elements: 10 20 30 40 50 The Array Elements are: 10 20 30 40 50
In this program, the recursive function printArray()
is calling itself again and again until it reaches the last element of the array.
The very first time, we manually call the printArray(arr, size, 0)
function. As the value of the index is 0 which is not equal to the size of the array i.e. 5, it prints the array element at index 0 and then again calls itself by incrementing the value of the index by 1 i.e. printArray(arr, size 1)
, printArray(arr, size, 2)
and so on.
These function calls continue until the value of the index becomes equal to the size of the array i.e. 5.
I hope you will find this article helpful. Thanks for reading.