Monday, December 24, 2007

Recursions to Non Recursions

Recursive routine

<type>funname0(para1, para2,...)
{
Code1;
if (cond1)//termination condition
{
Code_if;
return value;
}
Code2;
p = funname0(t1,t2...); //1
Code3;
k = funname0(p1,p2...); //2
code4;
return val;
}

Non Recursive Routine
<type>funname1 (para1, para2,...)
{
<type>extra;
/*
define stack with (all the data, which is visible to any of the recursive call)+
int funno(say)(signifying the which call has pushed this data );
*/
while(true)
{
while(true)
{
{All data declaration}
Code1;
if (cond1)//termination condition
{
Code_if;
extra = value;
break;
}
Code2;
// all pre operations(in call) should be done here //1

//Push all the data that is visible to any successive recursive call //1
//push 1 to funno
para1 = t1;
para2 = t2;
...
}
if(!stack.empty())
{
//pop out the values from stack to corresponding variables //1
switch(funno)
{
case 1:
p = extra;
// all post operations (in call)should be done here //1
Code3;

//all pre operations(in call) should be done here //2
//push all variables into stack, visible to any successive recursive calls //2
//push 2 to funno
para1 = p1;
para2 = p2;
...
break;
case 2:
k = extra;
// all post operations (in call)should be done here //2
code4;
extra = val;
break;
default:
}
}
else
return extra;
}
}