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?
n-1as 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).