How to Reverse an Array Recursively in C Language

In this tutorial, we want to code an array inversion function recursively. It turns out that the recursive method is more difficult compared to the iterative, but a recursive program is more formal.
To begin with, we need to define the cases of recursion. First, you need to write the program of the iterative method to understand.

invert elements of an array in C++

This figure explains in three steps the operation of the permutation between the i and the n-i,  the operation is repeated until half the length of the painting is reached. We have to repeat the operation only on the first half of the array otherwise we will swap the elements of the second half with those of the first half that have already been processed, and there we fall back on our starting array.

The following code swaps an array with the iterative method:

#include< conio.h> 
#include< stdio.h>

int main()
{
int i,n,temp;

printf("Array Size ");
scanf("%d",& n);
int t[n];

for(i=0; i< n; i++)
{
printf("t[%d]=",i);
scanf("%d",& t[i]);
}
i=0;
while(i< n/2)
{
temp = t[i];
//n-1 because the array starts with 0
t[i]=t[n-1-i];
t[n-1-i]=temp;
i++;
}

printf("\nInverse table: \n");
for(i=0; i< n; i++)
{
printf("\nt[%d]=%d",i,t[i]);
}
getch();
}
The execution of this code gives:

Invert an array in C with the recursive method

Now that we have our program for the iterative method, we're going to create a formal version. You are going to ask the question, what is it different from? Well! The recursive version is a function that calls on itself until it reaches the fulcrum. This recursive call is the equivalent of the loop in the iterative version.

You only need to translate the iterative program to get a recursive program. The fulcrum is the stop condition in the while loopi< n/2 (in the program we put i>=(n+1)/2 because when the function was called, the size of the array n-1 was decremented). i becomes the main parameter of the function because the stop test is done after each increment of i.

The following example shows how to recursively invert the elements of an array in C.

#include< conio.h> 
#include< stdio.h>

int* inverse(int[],int,int);

main()
{
int i,n;
printf("The size of the array");
scanf("%d",& n);
int t[n];
int *ti;
for(i=0; i< n; i++)
{
printf("t[%d]=",i);
scanf("%d",& t[i]);
}
ti=inverse(t,n-1,0);

printf("\nthe reverse array is: \n");
for(i=0; i< n; i++)
{
printf("\nt[%d]=%d",i,ti[i]);
}
getch();
}

int* inverse(int t[],int n, int i)
{
int temp;
if(i>=(n+1)/2 )
return t;
else{
temp = t[i];
t[i]=t[n-i];
t[n-i]=temp;
inverse return (t,n,i+1);
}
}
Compiling and executing this code results in the following: