0

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?

4
  • Formatting/indentation:( Commented Jul 1, 2017 at 9:59
  • Debugger............. Commented Jul 1, 2017 at 9:59
  • 3
    Just for kicks, try passing n-1 as your second parameter in your recursion, rather than changing it via pre-decrement. And note, you'll have to change something else too (left as exercise). Commented Jul 1, 2017 at 10:01
  • Thanks @WhozCraig got it (y) Commented Jul 1, 2017 at 10:08

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.