Recursive Sequence

This is a discussion on Recursive Sequence within the C Programming forums, part of the General Programming Boards category; I want to input a recursive sequence into a program for the computer to calculate it, but I am having ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    93

    Recursive Sequence

    I want to input a recursive sequence into a program for the computer to calculate it, but I am having some trouble doing so.

    Does anyone have any bright ideas to represent this sequence?

    a_n = sqrt(x)

    a_n+1 = sqrt(x + a_n)

    This is my code...thanks for any input.

    Code:
    #include <stdio.h>
    #include <math.h>
    
    float sequence (float x, int recurse);
    
    int main()
    {
          float limit;
    
    
    
          limit = sequence(3, -20);
    
          printf("%f", limit);
          getchar();
          return 0;
    }
    
    float sequence (float x, int recurse)
    {
         float answer;
    
         if ( recurse )
         {
            answer = sqrt(x + sequence(answer, recurse++) );
    
         }
    
         else
             return answer;
    }

  2. #2
    Super Moderater.
    Join Date
    Jan 2005
    Posts
    374
    For something so simple, consider not even using a recursive function.


  3. #3
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Where's the fun in that, treenef, if he's trying to learn recursion?

    If recurse is not negative, your function will run so long that that recursive function will probably cause you problems.

    Try to return the value without storing it in a temporary variable. This will save space and make it easier for your compiler to optimize it.

    http://en.wikipedia.org/wiki/Tail_recursion
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Immediate programming help! Please!
    By xMEGANx in forum C++ Programming
    Replies: 6
    Last Post: 02-20-2008, 11:52 AM
  2. sequence
    By braddy in forum C Programming
    Replies: 2
    Last Post: 03-30-2006, 01:15 PM
  3. difference between recursive and iterative
    By Micko in forum C Programming
    Replies: 33
    Last Post: 07-06-2004, 09:34 PM
  4. wsprintf and format specifiers
    By incognito in forum Windows Programming
    Replies: 2
    Last Post: 01-03-2004, 09:00 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21