# Recursion

• 10-26-2008
arctic_blizzard
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
• 10-26-2008
tabstop
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).
• 10-26-2008
Salem
1/n is going to be 0, for any n except 1.
Perhaps use doubles rather than ints?
• 10-26-2008
arctic_blizzard
yeah, i should've picked up on that...lol

I usually always use double for my assignments, just in case.
• 10-26-2008
arctic_blizzard
There is still something wrong with my equation...I have tried several iterations with the same result. Any hints?
• 10-26-2008
tabstop
You did remember to change your printf specifier to &#37;f when you changed the return type to double, right?

Edit: Also your final answer is probably 1.0 too large, since your base case is incorrect.
• 10-26-2008
arctic_blizzard
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.
• 10-26-2008
tabstop
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;     }```
• 10-26-2008
arctic_blizzard
works perfectly, thanks

wow - that one decimal place makes all the difference?
• 10-26-2008
tabstop
That's what we said at the beginning -- 1/n is always zero, except when n is 1.