Thread: Homework: Recursive Function Not Displaying Correct Sequence Request

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    70

    Homework: Recursive Function Not Displaying Correct Sequence Request

    That was a bad title, but hopefully I can clear it up here.

    Ok, so the assignment is to use a recursive function to display a request for a certain position in the Fibonacci Sequence (0, 1, 1, 2, 3, 5, 8, 13...)

    The program I have written works, but it displays the wrong number in sequence. The book says that when you enter "8" you should receive "13", which is correct in the order of the sequence, though my program is producing "21" which is the next number in the sequence.

    I tested it with a few more numbers and when I enter "7" it produces "13" and when I enter "6" it produces "8" and so on.

    Can anyone help me out with why it is calculating one above instead of the right number?

    Code:
    //Cameron Taylor
    
    #include <stdio.h>
    
    int main(){
    
        int n, result;
        int Fib(int);
    
            printf("Enter the number in sequence you are looking for: ");
            scanf("%d", &n);
    
        result = Fib(n);
    
            printf("\n The position in the sequences result is %d.\n", result);
    
        return 0;
    }
    
        int Fib(int n){
    
            if (n < 2)
                return (n);
            else 
                return (Fib(n-1) + Fib(n-2));
    }
    thanks!
    Last edited by Cameron Taylor; 07-01-2013 at 05:21 PM.

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    If the book wants them to be numbered incorrectly then just pass n-1 to Fib instead of n.
    Usually fib(0) = 0 and fib(1) = 1, so fib(8) = 21 as you have it now.

  3. #3
    Registered User
    Join Date
    Jun 2013
    Posts
    70
    Quote Originally Posted by oogabooga View Post
    If the book wants them to be numbered incorrectly then just pass n-1 to Fib instead of n.
    Usually fib(0) = 0 and fib(1) = 1, so fib(8) = 21 as you have it now.
    Ok, cool. I will submit both with a note for the assignment then. Just to clear it up. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recursive sequence
    By Tobias Mihel in forum C++ Programming
    Replies: 9
    Last Post: 06-02-2013, 08:19 AM
  2. Replies: 4
    Last Post: 02-10-2011, 02:50 PM
  3. Make Recursive function 'Tail-Recursive'
    By dp2452 in forum C Programming
    Replies: 7
    Last Post: 12-04-2009, 10:13 AM
  4. my HTTP request handler code correct?
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 04-25-2008, 04:01 AM
  5. Recursive Sequence
    By Beast() in forum C Programming
    Replies: 2
    Last Post: 04-26-2005, 06:42 AM