By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,369 Members | 950 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,369 IT Pros & Developers. It's quick & easy.

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

P: 1
// 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 << " ";
}
}
May 24 '18 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
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.
May 24 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.