Recursion

This is a discussion on Recursion within the C Programming forums, part of the General Programming Boards category; I am having difficulty with an assignment that has to deal with recursion in C. We were asked to create ...

1. Recursion

I am having difficulty with an assignment that has to deal with recursion in C.

We were asked to create a program (using recursion) to sum up a harmonic series.

This is what I have so far:
Code:
```#include <stdio.h>

long Harmonic ( int n );
int main()
{
int seriesSize;
printf("This program prints a harmonic series.\n");
printf("How many numbers do you want?\n");

scanf("%d", &seriesSize);

printf ("The sum of this harmonic series is: " "%ld\n", Harmonic(seriesSize));

system("pause");
}

long Harmonic ( int n )

{
long result;
if ( n == 0 )
result = 1;
else
result =(Harmonic(n-1)+(1/n));
return result;

}```
I am having trouble with the output, it doesn't return the correct value.

Is my harmonic equation incorrect? Where am I going wrong?

~AB

2. 1/n = 0 in all the cases where you do that division (well, 0 remainder 1, but you didn't ask for the remainder). If perhaps you want a decimal, you need to do 1.0/n. Also, you don't want an integral return type (long is an integer), but one of the floating-point types (float or double).

3. 1/n is going to be 0, for any n except 1.
Perhaps use doubles rather than ints?

4. yeah, i should've picked up on that...lol

I usually always use double for my assignments, just in case.

5. There is still something wrong with my equation...I have tried several iterations with the same result. Any hints?

6. You did remember to change your printf specifier to &#37;f when you changed the return type to double, right?

7. I've tried both of these base cases

if n==0
return 0

if n==1
return 1

and neither come up with a result even close to what it is supposed to be.
I have also tried other recursive steps:

(1/(Harmonic(n-1)))

1 + (1/(Harmonic(n-1)))

I have no idea why this is not working.

8. Code:
```#include <stdio.h>

double Harmonic ( int n );
int main()
{
int seriesSize;
printf("This program prints a harmonic series.\n");
printf("How many numbers do you want?\n");

scanf("%d", &seriesSize);

printf ("The sum of this harmonic series is: " "%f\n", Harmonic(seriesSize));

system("pause");
}

double Harmonic ( int n )

{
double result;
if ( n == 1 )
result = 1;
else
result =(Harmonic(n-1)+(1.0/n));
return result;

}```

9. works perfectly, thanks

wow - that one decimal place makes all the difference?

10. That's what we said at the beginning -- 1/n is always zero, except when n is 1.