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, RecursionLogic 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,
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 ;)
You may also like
- Function and recursion programming exercises index.
- Array and matrix programming exercises index.
- C program to find sum of elements of array using recursion.
- C program to find power of any number using recursion.
- C program to print all natural numbers from 1 to n using recursion.
- C program to print all even or odd numbers using recursion.
- C program to find sum of all even numbers in a given range using recursion.
- C program to find reverse of any number using recursion.
- C program to check whether a number is palindrome or not using recursion.
- C program to find GCD(HCF) of any two numbers using recursion.
- C program to find LCM of any two numbers using recursion.
- C program to find maximum or minimum of two numbers using function.
- C program to check prime, armstrong and perfect number using functions.