Search code examples
carraysrecursionreverse

Reverse array with recursion in C programming


I was having some problem when trying to do a reverse array using recursion. Here is the function prototype:

void rReverseAr(int ar[ ], int size); 

And here is my code:

int main()
{
    int ar[10], size, i;

    printf("Enter array size: ");
    scanf("%d", &size);
    printf("Enter %d numbers: ", size);
    for (i = 0; i<size; i++)
        scanf("%d", &ar[i]);
    rReverseAr(ar, size);
    printf("rReverseAr(): ");
    for (i = 0; i<size; i++)
        printf("%d ", ar[i]);
    return 0;
}

void rReverseAr(int ar[], int size) {
    int start = 0, end = size - 1, temp;
    if (start < end) {
        temp = ar[start];
        ar[start] = ar[end];
        ar[end] = temp;
        start++;
        end--;

        rReverseAr(ar, size - 1);
    }       
}

The expected output should be when user entered 1 2 3 and it supposed to return 3 2 1. However, with these code, the output that I am getting is 2 3 1.

Any ideas?


Solution

  • Your code is almost right. The only problem is that instead of "shrinking" the array from both sides, you shrink it only from the back.

    The recursive invocation should look like this:

    rReverseAr(ar + 1, size - 2);
    

    You do not need to increment start or decrement end, because their values are not used after modification.