# 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

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