Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursive call

Status
Not open for further replies.

yogpatel

Programmer
Jan 30, 2010
7
IN
Hello, Anybody tell me how this recursive call works and its answer

int fun(int *a, int n)
{
if (n<=0)
return 0;
else if(*a %2==0)
return (*a +fun(a+1,n-1));
else
return (*a-fun(a+1,n-1));
}
int main()
{
int a[]={12,7,13,4,11,6};
printf("%d",fun(a,6));
return 0;
}
Thanx.
 
The easiest way is to put print statements in the code. Add a level to show how deep it is nesting. Look at what you get when it reenters the routine.
Code:
int level;
int fun(int *a, int n)
{
   int ii, result;
   /* Print the parameters */
   ++level;
   printf ("level = %d, n = %d, a = ", level, n);
   for (ii = 0; ii < n; ++ii)
      printf (" %d", a[ii]);
   printf ("\n");

   if (n<=0)
      result = 0;
   else if(*a %2==0)
      result = (*a +fun(a+1,n-1));
   else
      result = (*a-fun(a+1,n-1));

   printf ("level = %d, result = %d\n", level, result);
   --level;
   return result;
}
int main()
{
    int a[]={12,7,13,4,11,6};
    int result;

    level = 0;
    result = fun(a,6);
    printf("%d",result);
    return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top