You should post the code as plain text in code bbcode tags, with only whitespace for the formatting rather than any additional markup. The forum software will then insert syntax highlighting and line numbering to make the code easier to read:
Code:
#include <stdio.h>
#define MAX 5
int func( const int a[ ], size_t b );
int main( void )
{
int c;
int p[MAX] = {1, 2, 3, 4, 5};
c = func( p, MAX );
printf( "Result is %d\n", c );
}
int func( const int a[ ], size_t b )
{
if( b == 1 )
return a[0];
else
return a[b-1] + func( a, b-1 );
}
Originally Posted by
asiankappa47
Could someone explain to me how this code gets to print the value 15?
Let's say you want to write a function to sum the elements of an integer array. You could of course write a loop and keep track of the current sum, but what if you were lazy and had access to another function that would sum the elements of the array, except for the last element? Then your job is easy: you just call that other function, then add its return value to the last element, and tada! return the result and you're done. Of course, if your array only has one element, you don't need to call that other function, but can just return that one element itself. This is what func is doing, except that "other function" is func itself, i.e., recursion.
Of course, this is a somewhat more high level view of what func is about. It would still be instructive for you to trace through what is happening step by step yourself.