+ 1
tail recursion - power function
I try to write power function using tail recursion but I don't get the right answer what is wrong? // tail function long int TailRec (int number , int p_number , int counter = 1 ){ if (p_number == 1) return counter ; else TailRec (number , p_number-1 , number*counter ); } //main function int main() { long int result = TailRec(2,2) ; cout<<result ; } //out put 2
3 Answers
+ 1
change your test to
if (!p_number) return counter;
And it will work fine
+ 1
number! =1 for first run.
so it goes to else and returns 2*1
0
thank u guys, I fixed that silly mistake but i have and another question is this really a tail recursive function?