How can I print 0 1 1 2 3 5 8 ???

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Yeva
    New Member
    • May 2018
    • 1

    How can I print 0 1 1 2 3 5 8 ???

    // Example program
    #include <iostream>
    using namespace std;

    bool isFibonacci( int n, int a = 1, int b = 1 )
    {
    if(n == 0 || n == 1 ) return true;
    int nextFib = a + b;
    if( nextFib > n ) return false;
    if( nextFib == n ) return true;

    return isFibonacci( n, b, nextFib );
    }

    int main()
    {
    for(int i = 0; i<=10; ++i)
    {
    if(isFibonacci( i))
    cout << i << " ";
    }
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Your isFibonacci function never uses the last two arguments. They are defaulted to 1 and are never changed.


    What you should to is generate Fibonacci numbers and then print them.

    In main() you use 2 int variables initialized to 0 and 1.

    Add these numbers to get the next Fibonacci value.


    Move the second variable (1) to the first variable and move the next Fibonacci value to the second variable.

    These two variables are the previous two Fibonacci values.

    Repeat the previous two steps for the next Fibonacci value.

    Put the steps in a loop to generate the desired number of Fibonacci values.

    Comment

    Working...