-1

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 :)

sahar
  • 3
  • 2
  • 1
    There is no mention of the programming language being targeted, or a code example of what has been tried so far. – tarilabs Mar 04 '20 at 21:05
  • 1
    @tarilabs sorry about that , how about now ? – sahar Mar 06 '20 at 09:10
  • Welcome to SO. `THIS is where the problem is`: **what** is the problem? You need to describe things (build? run? error message ?). And you should read some of this: https://stackoverflow.com/help/asking . And indent your code so it is readable. – kebs Mar 06 '20 at 09:14
  • And you seem to mix up C and C++. Those are two different languages. You use a C header file, so you should tag your question as such. – kebs Mar 06 '20 at 09:16

1 Answers1

0

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));
}
Botje
  • 26,269
  • 3
  • 31
  • 41