Invert the Position of Elements in an Array
This lesson will help us invert the position of elements in an array using recursion.
Invert the Position of Elements #
Given an array, you have to reverse the position of array elements.
Implementing the Code #
The following code explains the concept of reversing the elements of an array using recursion.
Experiment with the code by changing the array
elements and size
to see how the answer changes.
Press + to interact
#include <iostream>using namespace std;//Recursive function for Reversing arrayvoid reverseArray(int arr[], int startIndex, int endIndex){//base caseif (startIndex >= endIndex) //if the middle of array is reachedreturn;int temp = arr[startIndex]; //swap value at start with value at the endarr[startIndex] = arr[endIndex];arr[endIndex] = temp;// recursive casereverseArray(arr, startIndex + 1, endIndex - 1);//call the recursive function}//Driver functionint main(){int array[5]={1,2,3,4,5};//define the arrayint size=5;//define the size of arrayreverseArray(array,0,size-1); //call the recursive functioncout<<"Reversed Array:";for (int i=0;i<5;i++)cout<<array[i];//print the arrayreturn 0;}
Understanding the Code #
A recursive code can be broken down into ...