
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(n1)+(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?
Thanks for your help in advance!
~AB

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 floatingpoint types (float or double).

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

yeah, i should've picked up on that...lol
I usually always use double for my assignments, just in case.

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

You did remember to change your printf specifier to %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.

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(n1)))
1 + (1/(Harmonic(n1)))
I have no idea why this is not working.

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(n1)+(1.0/n));
return result;
}

works perfectly, thanks
wow  that one decimal place makes all the difference?

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