Write a recursive function which will print an array in forward and backward order (depending on a parameter). The signature of the function should be
/* If the array is 1 2 3 4 5, then Output should be * 1 2 3 4 5 - if (forward == true) * 5 4 3 2 1 - if (forward == false) */ void printArray(int * arr, int n, bool forward);
Solution:
Before reading this post, learn about recursion, how recursion happens internally and Head & Tail recursion.
Code:
void printArray(int * arr, int n, bool forward)
{
if(n<=0)
return;
if(forward)
{
printf("%d ", arr[0]);
printArray(arr+1, n-1, forward);
}
else
{
printf("%d ", arr[n-1]);
printArray(arr, n-1, forward);
}
}