Recursion calling

How to know when the work should be done ? Like should i do the work while the stack is building or while the stack is falling.

@shikhar07,
When you enter a recursive function, stack will build when a recursive function again calls the recursive function. A stack will start to fall when a recursive function will hit base case and return some value

I dont think you have understood what i am trying to ask here. I have understood how recursion works but what i am asking is once presented with a recursive question , how must one approach it ? should we do the work first and then call recursion or should we call recursion and then do the work . To explain my point better i have added a piece of code below:-
public static boolean isSortedBefore(int arr[],int si)
{
if(si==arr.length-1)
{
return true;
}
if(arr[si]>arr[si+1])
{
return false;
}
else
{
boolean res=isSortedBefore(arr,si+1);
return res;
}
}
public static boolean isSortedAfter(int arr[],int si)
{
if(si==arr.length-1)
{
return true;
}
boolean output=isSortedAfter(arr,si+1);
if(output==true)
{
if(arr[si]>arr[si+1])
{
return false;
}
else
{
return true;
}
}
else
{
return output;
}
}

@shikhar07,
you can do either depending upon the question. See if you first do the work and then call the recursive function, all the work will be done starting from the last call. If you first do the work then you need to store your answer and then give the updated call.

1 Like