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.
long double sum(long double n)
long double d = (1/n) + sum(n-1);
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.
long double sum2(long double n)
long double d = 0;
d += 1/i;
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
as you can see, this particular main calls the second function.
long double n;
long double ans;
cout << "Enter your value of n: ";
cin >> n;
ans = sum2(n);
cout << "The sum is " << ans << endl;
cout << "Value of n makes no sense!";