Home > Backend Development > C++ > body text

C/C++ program to find the nth Fibonacci number?

WBOY
Release: 2023-09-12 18:01:02
forward
766 people have browsed it

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
Copy after login

Instructions

0+1=1
1+1=2
1+2=3
2+3=5
Copy after login

Use a For loop to sum the first two items as the next item

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 << " ";
   }
}
Copy after login

Output

0 1 1 2 3 5 8 13
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template