How to make Fibonacci series on C++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

How to make Fibonacci series on C++?

7th Nov 2016, 7:59 PM
Király Zoltán
Király Zoltán - avatar
8 Answers
+ 18
http://www.sololearn.com/app/sololearn/playground/cX1b84CsDDrF/ #include <iostream> using namespace std; int fibonacci_rec(int i, int curr, int prev) { if (i == 0) {return prev;} if (i == 1) {return curr;} return fibonacci_rec(i-1, curr+prev, curr); } int fibonacci(int i) { return fibonacci_rec(i, 1, 0); } int main() { int n; cout << "Fibonacci" << endl; cout << "Please enter a number: "; cin >> n; cout << n << endl; cout << "fib(" << n << ") = " << fibonacci(n) << endl; return 0; }
7th Nov 2016, 8:11 PM
Zen
Zen - avatar
+ 7
Here is the iterative method in case you prefer it: int fib(int n) { int prev=0, curr=1, aux; for(auto i=0; i <n; ++i) { aux=curr; curr+=prev; prev=aux; } return curr; }
8th Nov 2016, 1:00 AM
Seckar
Seckar - avatar
+ 7
Great fibonacci function, just in 3 lines! https://code.sololearn.com/cB7CscN8bVm8/ ⭐️⭐️⭐️⭐️⭐️ int fibo(int n) { if (n <= 2) return 1; return fibo(n - 1) + fibo(n - 2); } int main() { int whichFibo; cin >> whichFibo; cout << fibo(whichFibo); return 0; } ⭐️⭐️⭐️⭐️⭐️
16th Dec 2016, 9:28 AM
$machitgarha
$machitgarha - avatar
+ 3
@zen personally i found this recursiv verson so elegant:)
12th Nov 2016, 8:01 PM
Benedek Máté Tóth
Benedek Máté Tóth - avatar
+ 2
@zen i hav jus modified ur code... #include <iostream> using namespace std; int fibonacci(int i, int curr, int prev) { if (i == 0) {return prev;} if (i == 1) {return curr;} return fibonacci(i-1, curr+prev, curr); } int main() { int n; cout << "Fibonacci" << endl; cout << "Please enter a number: "; cin >> n; cout << n << endl; cout << "fib(" << n << ") = " << fibonacci(n,1,0) << endl; return 0; }
16th Dec 2016, 6:54 AM
Deekshith Banjan
Deekshith Banjan - avatar
+ 2
lude <iostream> using namespace std; int main() { int f=0,s=1,next,i,no; cout<<"Enter number of terms:"<<endl ; cin >>no; cout <<"First "<<no <<"terms of fibonacci series"; for(i=0;i<no;i++) { if (i<=1) { next=i; } else { next=f+s; f=s; s=next; } cout<< next<<endl ; } return 0; }
16th Dec 2016, 8:08 AM
Syed Naqvi
Syed Naqvi - avatar
+ 2
THX:
18th Jan 2017, 3:18 PM
Király Zoltán
Király Zoltán - avatar
+ 1
#include <iostream> using namespace std; int fib(int n) { static int f1=0,f2=1,t; if(n==0) return 0; else { cout<<f1<<endl; t=f1; f1=f2; f2=t+f2; n--; return fib(n); } } int main() { int n; cin>>n; cout<<"Entered no is:"<<n<<endl; cout<<"The fibonacci series:"<<endl; fib(n); return 0; }
16th Dec 2016, 6:42 AM
Deekshith Banjan
Deekshith Banjan - avatar