iteration and recursion question

Hi all, me again :)

I had someone ask me whether the sum of 1/n as n tends to infinity converges or not(that is 1+1/2+1/3+1/4+...+1/n). Now as a mathematician I can show that it doesn't quite easily. But I thought I would give it a go in c++. While it won't prove anything, it can demonstrate that for large numbers there doesn't seem to be an upper bound, plus I thought it would be fun!

So I created a couple of functions, one using recursion and the other using iteration. Here they are.

Code:

`long double sum(long double n)`

{

if(n==1.)

{

return 1.;

}

long double d = (1/n) + sum(n-1);

return d;

}

Code:

`long double sum2(long double n)`

{

long double d = 0;

for(double i=1;i<=n;i++)

{

d += 1/i;

}

return d;

}

I then wrote a simple main which checked to make sure n was greater than or equal to one and, if it was, would call one of these functions to show the sum.

Now both the functions seem to work except for one difference. When I set n to one million and the main calling the first function, the program simply closes. But when I tell the main to call the second (iterative) function, it works fine.

I thought it might be the variable types I was using (which is why I changed them to long double) but it didn't seem to make a difference, so I'm simply wondering what the difference is?

For completeness, here is the main

Code:

`int main()`

{

long double n;

long double ans;

cout << "Enter your value of n: ";

cin >> n;

if(n>=1)

{

ans = sum2(n);

cout << "The sum is " << ans << endl;

}else

{

cout << "Value of n makes no sense!";

}

getch();

return 0;

}

as you can see, this particular main calls the second function.

Kind Regards

Stonehambey