Print all repeating characters in a string
August 8, 2012
Majority Element of an Array (Moore's Algorithm)
August 8, 2012

Print array in the forward and backward direction recursively

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);
        }
    }

 

Leave a Reply

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