Thursday, June 29, 2006

Recursion

yes recursion ,thinking iam mad iam not .

Recussion are of two types:-
1.General Recursion .
2.TailEnd Recursion .

1.General Recursion :- This is the one in which the whole part of the function needs to be activate till the last function call:
// For the Factorial
int Generalrecusrion(int iVal)
{
if (iVal==0)
return 0;
else if (iVal==1) return 1;
else return iVal * Generalrecusrion(iVal-1);
}

2. Tail Recursion :-
The function will not be active bcoz the function call to the next recursion will take off and terminate the prev Function .
// For the Factorial
int Tailrecursion(int n, int a )
{
if (n < 0)
return 0;
else if (n == 0)
return 1;
else if (n == 1)
return a;
else return Tailrecursion(n - 1, n * a);
}
// For the harmonic Progression// 1 + 1/2 + 1/3 + 1/4+...
float Harmonic(float n ,float iii )
{
if (n < 0) return 0;
else if (n == 0) return 1;
else if (n == 1) return iii;
else {
float fVal = iii + float (1/n );
return Harmonic(n - 1, fVal );
}
}
Even the compiler will help us in optimizing the following code to more level.

No comments: