I'm trying to calculate the Harmonic Series with TAIL recrusion,simple recrusion works but not the terminal version , This is the simple recrusion version :
#include<stdio.h>
float calcul(int n)
{if(n==1)
return 1;
else
return (1/float(n)+(calcul(n-1)));
}
main()
{int i,n;float h,t;
t=1;
printf("type in a number :\n");
scanf("%d",&n);
printf("H(%d)= %.3f",n,calcul(n));}
this is TAIL recrusion but it doesn't work :
#include<stdio.h>
float calcul(int n,float t)
{if(n<2)
return 1;
else
return calcul(n-1,t+(float(1)/float(n)));
}
main()
{int n;
float t;
t=1.00;
printf("type in a number :\n");
scanf("%d",&n);
printf("H(%d)= %.3f",n,calcul(n,t));}
I'm using c please help me :)
The key point of tail recursion is that you all recursive calls are in tail position, which is not the case for you (you still have to do + after the recursive call).
Fix that by introducing an accumulator that you return in the base case or update in the recursive case:
float calcul(int n) {
return calcul(n, 1);
}
float calcul(int n, float acc) {
if (n == 1)
return acc;
else
return calcul(n-1, acc + 1 / float(n));
}