CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2007
    Posts
    34

    recursive function

    I am trying to write the body of a recursive function in pseudo code but it has been years since I've done any coding.
    a,b,a+b,a+2b,2a+3b,3a+5b...
    is the pattern. I see that this looks like a fibonacci sequence where the previous term is added to the current term to get the next term but I can't express this in any kind of code. Can anyone help me please.

  2. #2
    Join Date
    Mar 2010
    Posts
    56

    Re: recursive function

    Code:
    void DoIt(int a,int b)
    {
    	static int LastTerm=a;
    	static int CurrentTerm=b;
    	int Temp=CurrentTerm;
    	CurrentTerm=LastTerm+CurrentTerm;
    	LastTerm=Temp;
    	cout<<CurrentTerm<<endl;
    	string s;
    	cin>>s;
    	if(s=="yes")
    	{
    		DoIt(a,b);
    	}
    }
    I think it should work.
    It doesn't print the first two numbers.

  3. #3
    Join Date
    Aug 2008
    Location
    Scotland
    Posts
    379

    Re: recursive function

    Say you have a function DoIt(a,b,n), where n is the term in the series you want to find.

    Then, maybe;

    If n = 1, return a.
    If n =2, return b;
    If n = 3, return a + b
    If n = 4 or more, return DoIt(b,a+b,n-1)

  4. #4
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    4,626

    Re: recursive function

    Actually it is a fibonacci sequence, but with set start values rather than 0,1 as start values.

    the shorthand results would be:

    myfib(0,a,b) = a
    myfib(1,a,b) = b
    myfib(n,a,b) = myfib(n-1,a,b) + myfib(n-2,a,b)


    In actual code:

    Code:
    int myfib(int TermNum, int a, int b)
    {
       if (nTermNum==0)
          return a;
      else if (nTermNum==1)
        return b;
      else
           return myfib(nTermNum-1, a, b) + myfib(nTermNum-2, a, b);
    }
    The above of course is somewhat less than efficient since it'll split into 2 calls retracing back each time through the recursive sequence, this is the same problem as when you would program the actual fibonacci sequence recursively. It's typically better to solve this linearly without recursion.
    Code:
    int myfib(int TermNum, int a, int b)
    {
           if (nTermNum==0)
          return a;
      else if (nTermNum==1)
        return b;
      else
      {
          do 
          {
              nTermNum--;
              int next=a+b;
              a=b;
              b=next;
          }
          while (nTermNum>1)
    
          return b;
      }
    }
    Last edited by OReubens; March 19th, 2010 at 08:05 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured