Reverse an Array using Recursion in C++

In this tutorial, we will learn how to reverse the elements of an array using Recursion in C++.

When a function calls itself then the function is known as a Recursive Function and this procedure is known as Recursion. A recursive function runs until the base case is not executed.

To Reverse an Array means to arrange the elements of the array in the opposite order in which they were present earlier.

Let us see how this algorithm works.

Algorithm to Reverse the array using Recursion

  1. Let arr be the array to be reversed whose size is n.
  2. We define a function named recfun which has 3 parameters for an index, for the array and for the size of the array.
  3. Then we check whether the index is greater than or equal to half of the size of the array using an if condition.
  4. If yes then the function ends.
  5. Else we swap the values of the array arr at index [ i ] and [ n-1-i ].
  6. Then we call the function again, this time with the next index.
  7. This process continues until the base condition is not true.
  8. Now we define the main function.
  9. Call the function recfun passing parameters such as starting index, array address and size of the array.
  10. Then we print the Reversed Array using a for loop.

For example: If the input is [1 , 5 , 8 , 3 , 6]

Then the Output would be [6 , 3 , 8 , 5 , 1 ]

C++ Code:

#include<bits/stdc++.h>
using namespace std;

void recfun(int i,int arr[],int n)
{
    if(i>=n/2)
        return;

    swap(arr[i],arr[n-1-i]);

    recfun(i+1,arr,n);
}

int main()
{
    int arr[]={5,4,8,3,6,1};
    recfun(0,arr,6);

    for(int i=0;i<6;i++)
    {
        cout<<arr[i]<<" ";
    }

    return 0;
}

Output

1 6 3 8 4 5

Leave a Reply

Your email address will not be published. Required fields are marked *