Write a C, C++ program to reverse an array using recursion. Given an input array, we have to write a code that reverse an array using recursion.
I assume you are familiar with the concept of recursion and the difference between iteration and recursion. Let's quickly go through the concept of recursion.
In recursion, A function call itself until the base condition is reached.
Reverse a number using recursion
Let's assume user has input following array values.
I already discussed how to reverse an array using iterative approach in my previous post. In this post, we'll write a code to reverse an array using recursion.
Output :
Enter the size of an array 5
Enter an element of an array
2 3 5 6 7
Reverse of an array is
7 6 5 3 2
Swap two numbers using third variable.
Swap two numbers using pointer(call by reference).
Swap two numbers without using third variable.
I assume you are familiar with the concept of recursion and the difference between iteration and recursion. Let's quickly go through the concept of recursion.
In recursion, A function call itself until the base condition is reached.
Reverse a number using recursion
// Input array
int arr[] = {3,2,1,7,8}
// Reverse of an input array
arr[] = {8,7,1,2,3}
I already discussed how to reverse an array using iterative approach in my previous post. In this post, we'll write a code to reverse an array using recursion.
C Program to Reverse an Array using Recursion
#include <stdio.h>
int reverse(int arr[],int start,int end){
int temp;
// if start is less than end
if(start < end){
/* Swap the position of an element. */
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
/*calling itself
*Incrementing start and decrementing end
*/
reverse(arr, start+1, end-1);
}
return 0;
}
int main(void) {
// Decare an array
int arr[] = {3,2,1,7,8};
int n = 5;
/* Call reverse method */
reverse(arr, 0, n-1);
printf("Reverse of an array \n");
for(int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
return 0;
}
C++ Program to Reverse an Array using Recursion
#include <iostream>
using namespace std;
int reverse(int arr[], int start, int end) {
int temp;
if(start < end) {
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// recursive function call
reverse(arr, start+1, end-1);
}
return 0;
}
int main() {
int n, arr[100], i;
cout << "Enter the size of an array \n";
cin >> n;
cout << "Enter an element of an array \n";
for(i = 0; i < n; i++) {
cin >> arr[i];
}
reverse(arr, 0, n-1);
cout << "Reverse of an array is \n";
for(i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output :
Enter the size of an array 5
Enter an element of an array
2 3 5 6 7
Reverse of an array is
7 6 5 3 2
Swap two numbers using third variable.
Swap two numbers using pointer(call by reference).
Swap two numbers without using third variable.

No comments:
Post a Comment