Click here to Skip to main content
16,020,186 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys
i need to analyze this function:

a=5,2,6,3,9,1 ; sz=6 ; k=20
C#
int f4(int *a, int sz, int k)
{
  if(sz>0 && k!=0){
    if(f4(a+1,sz-1,k-a[0]))
      return 1;
    else
      return f4(a+1,sz-1,k);
  }
  return (k ? 0 : 1);
}

but idk how to follow after all of the returns, pls explain it to me,THX.
Posted
Updated 11-Feb-13 2:12am
v2
Comments
E.F. Nijboer 11-Feb-13 7:38am    
The only return you need to follow is that of the if statement. Write them down in a tree like fashion so you keep track of how deep you are.

I'm not sure what's confusing you here, perhaps you just need to unpack the code a bit. If you want to know what it's trying to achieve you find that out by reading the documentation or asking the author, the code can only tell you want it does to its parameters not why anyone would want to do that.

The C++ version below should be easy enough to understand.
C#
bool f4( int* array, int size, int k )
{
  if( size > 0 && k != 0 )            //if there is anything to process
  {
    if( f4( array + 1, size - 1, k - a[ 0 ] ) )  //if processing all the elements after the first one against a k of ( k - first element ) returns true then
    {
      return true;
    }
    else                                       //otherwise
    {
      return f4( array + 1, size - 1, k );     //return the result of processing all the elements after the first one against k itself
    }
  }
  return ( k ? false : true ); //In the no-more-to process case return the inverse of k, true if k is 0, false otherwise
}


What all this is to achieve I do not know but if you really badly want to find out you can do it yourself on paper by following the steps or just single step your debugger while watching the stack.
 
Share this answer
 
That recursion works like all other recursions[^] do: you have to follow the code (with a debugger or, virtually, by inspection) to understand what happens.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900