D all parts for full poinnts thanks FOR POSITIVE FEEDBACK Co
D all parts for full poinnts thanks! FOR POSITIVE FEEDBACK
Consider the following implementation in the C language: int g(int x) {if (x == 1) {return 1;} return x*g(x-l);} Write down a tail recursive implementation of function g. You can use helper function in your solution. An \"optimizing\" compiler will often be able to generate efficient code for recursive functions when they are tail-recursive. Refer to activation record, briefly explain how a compiler may \"reuse\" the same activation record for your solution in a).Solution
a) tail recursive implementation of g
int g(int y,int acc)
{
if(y==1)
{
return acc;
}
else
{
return g(y-1,y*acc);
}
}
Calling above function from main while testing both functions...
int main() {
// your code goes here
int n=10;
cout<<\"Callin function g : \"<<g(n)<<endl;
cout<<\"Callin function g with tail recursion: \"<<g(n,1)<<endl;
return 0;
}
b) A compiler can usually optimize a tail-recursive function into a loop if the recursive function is the absolute final operation in the function. In the above example compiler can optimize as loop using control structure in tail recurive function as
while(x)
{
acc*=x;
x-=1;
}
return acc;
