Pb Vignesh
Pb Vignesh

Reputation: 185

Recursion array unexpected print value in C

Why does this print 1,1,2,3,4,5 instead of 1,2,3,4,5?

#include <stdio.h>
#include <stdlib.h>

void print(int a[5], int n)
{
    if(n > 0) {
        print(a, --n);
    }

    printf(" %d", a[n]);
}

int main()
{
   int n, a[] = {1,2,3,4,5};
   n = sizeof(a) / sizeof(a[0]);
   print(a, n);
   return 0;
}

And how would you code it to print 1,2,3,4,5 using recursion in that manner ie traversing from the last?

Upvotes: 0

Views: 43

Answers (1)

kfx
kfx

Reputation: 8537

The problem with your code is that you decrement n after the comparison in the if condition n > 0.

When print(a, 1) is called, the comparison n > 0 is true. Then n is decremented and, the recursive call is done and print(a, 0) evaluated. That fails the comparison and prints a[0] once. Then back in the calling function, a[0] is printed another time, since the local n after decrementing is also equal 0.

One way to fix it is to decrement n before doing the comparison with zero.

Upvotes: 3

Related Questions