The Fibonacci sequence is a series where the next term is the sum of the previous two terms.The first two terms of the Fibonacci sequence is 0 followed by 1.
In this problem, we will find the nth number in the Fibonacci series. For this we will calculate all the numbers and print the n terms.
Input:8 Output:0 1 1 2 3 5 8 13
Explanation
0+1=1 1+1=2 1+2=3 2+3=5
Using For loop to sum of previous two terms for next term
Example
#include<iostream> using namespace std; int main() { int t1=0,t2=1,n,i,nextTerm; n = 8; for ( i = 1; i <= n; ++i) { if(i == 1) { cout << " " << t1 ; continue; } if(i == 2) { cout << " " << t2 << " " ; continue; } nextTerm = t1 + t2 ; t1 = t2 ; t2 = nextTerm ; cout << nextTerm << " "; } }
Output
0 1 1 2 3 5 8 13