Write a function
to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence
the sum of two successive terms gives the third term. Following are the first few
terms of the Fibonacci sequence: 1 1 2 3 5 8 13 21 34 55 89...
//==========================================================================
#include<iostream>
void
fibonaci_sequence();
using namespace std;
void main()
{
fibonaci_sequence();//Prints first 25 terms of Fibonaci
Sequence.
}
void fibonaci_sequence()
{
int term[27];
term[0] = term[1] = 1;
cout<<term[0]<<"\t
"<<term[1]<<" \t";
for (int i = 2; i<25; i++)
{
term[i] = term[i-2]+term[i-1];
cout<<term[i]<<" \t";
}
cout<<endl;
}
//==========================================================================
Recursive Function to find any fibanacci term.
#include <iostream>
using namespace std;
int fib(int);
int main()
{
int x;
cout << "X: ";
cin >> x;
cout << fib(x) << endl;
return 0;
}
int fib(int term)
{
if (term == 1 || term == 2)
return 1;
else
return fib(term-1) + fib(term-2);
}
#include <iostream>
using namespace std;
int fib(int);
int main()
{
int x;
cout << "X: ";
cin >> x;
cout << fib(x) << endl;
return 0;
}
int fib(int term)
{
if (term == 1 || term == 2)
return 1;
else
return fib(term-1) + fib(term-2);
}
No comments:
Post a Comment