...

/

Invert the Position of Elements in an Array

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 array
void reverseArray(int arr[], int startIndex, int endIndex)
{
//base case
if (startIndex >= endIndex) //if the middle of array is reached
return;
int temp = arr[startIndex]; //swap value at start with value at the end
arr[startIndex] = arr[endIndex];
arr[endIndex] = temp;
// recursive case
reverseArray(arr, startIndex + 1, endIndex - 1);//call the recursive function
}
//Driver function
int main()
{
int array[5]={1,2,3,4,5};//define the array
int size=5;//define the size of array
reverseArray(array,0,size-1); //call the recursive function
cout<<"Reversed Array:";
for (int i=0;i<5;i++)
cout<<array[i];//print the array
return 0;
}

Understanding the Code #

A recursive code can be broken down into ...