Recursion problems

Hey Everyone,

So I am trying to write a code that uses recursion to print out the sequence:

m(n) = 1/3 + 2/5 + 3/7 +...+n/(2n+1)...

my code looks like this:
#include <iostream>
using namespace std;

int m(int n)
{


double part = n/((2.0*n)+1.0);
double sum =0;
sum += part;
n--;

return m(n);
}
int main()
{
int n;

cout<<"Enter a value: "<<endl;
cin>>n;

if (n<1)
{return 0;}
else
{
return m(n);
}
}


and I am getting a Segmentaion Fault

Any suggestions
thanks
---Chad
Your program has infinite recursion - in other words, your recursive function just keeps on calling itself until you eventually overflow the stack and your program crashes.

You need to write a check into your recursive function which prevents it from calling itself ad-infinitum.
How do I do that?
Don't call m(n) as the return value from m(n).
If you are returning the summation of m(n) then you'll want to carry the current sum along
also you need to decrement and check the argument that sets the upper bounds of the summation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

double m(int n, double s = 0.0)
{
  double sum = s + (n/((2.0*n)+1.0));
  // ternary operator acts like if..then..else
  // (--n)             if we decrement n, is it still > 0?
  // ? m(n,sum)        if n is still > 0, recurse
  // : sum             if n is zero just return the sum
  return (--n) ? m(n,sum) : sum;
}

int main()
{
  int n;

  cout<<"Enter a value: "<<endl;
  cin>>n;

  if (n<1)
  {
    return 0;
  } else {
    double summation = m(n);
    cout << "Summation for m(n) where  n / (2n + 1) : " << summation << endl;
    return summation; // though this is odd since it will only return the integer portion
  }
}
Last edited on
You might want to explain the ternary operator. Most beginners don't understand that.
In simplest terms, recursive functions need a "base case". This is the case that causes recursive functions to stop recursing. This can be in the form of an if statement at the beginning of the function, or a ternary return operation as Texan40 has shown, etc.
Topic archived. No new replies allowed.