Consider the following implementation in the C language int
Consider the following implementation in the C language:
int g (int x) {
if (x == 1) {
return 1;
}
return x*g(x-1);
}
a) (6pt) Write down a tail recursive implementation of function g. You can use helper function in your solution.
b) (4pt) 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
ANSWER:
GIVEN PROGRAM:
int g (int x) {
if (x == 1) {
return 1;
}
return x*g(x-1);
}
TAIL RECURSION
int g(int x){
return g(x,1);
}
int gTailRecursive(int x,int a){
if (x == 1) {
return a;
}
return gTailRecursive(x-1,x*a);
}
(b) :The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. The idea used by compilers to optimize tail-recursive functions is simple, since the recursive call is the last statement, there is nothing left to do in the current function, so saving the current function’s stack frame is of no use.
