I have a recursive function from a C book as follows:
void print(int a[], int n)
{ if (n<=0) return ;
printf("%d\n", a[0]);
print(&a[1], n-1);
}
I have run and this function prints all the element of the specified array. But I really do not understand how this function works so that I can print all elements of an array.
Can anyone give me a clear explanation, please?
&a[1]is the address of the second element of the array, which is effectively the address of the portion of the array after the first element. So after printing the first element of the parameter array,passes itself the remaining portion of the array, decreasing the length by one as well.
For example, if you call
printwith the array{1, 2, 3, 4, 5}andn == 5, the chain of events and calls is the following:{2, 3, 4, 5}andn == 4{3, 4, 5}andn == 3{4, 5}andn == 2{5}andn == 1{}andn == 0n<=0-> return