Home > Article > Backend Development > C/C++ program to find the nth Fibonacci number?
The Fibonacci sequence is a sequence of numbers in which the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1.
In this problem, we will find the nth number in the Fibonacci sequence. To do this, we will calculate all the numbers and print n items.
Input:8 Output:0 1 1 2 3 5 8 13
0+1=1 1+1=2 1+2=3 2+3=5
Use a For loop to sum the first two items as the next item
#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 << " "; } }
0 1 1 2 3 5 8 13
The above is the detailed content of C/C++ program to find the nth Fibonacci number?. For more information, please follow other related articles on the PHP Chinese website!