- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C/C++ Program for the n-th Fibonacci number?
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
Advertisements