In this program, we will learn how to make a C++ program of printing the Fibonacci Sequence. We will be learning two ways to make this program.
- Printing Fibonacci Sequence using loop
- Printing Fibonacci Sequence using Recursion
So, Let’s discuss these two ways one by one.
Printing Fibonacci Sequence using Loop
We will be using the for loop here.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<iostream> using namespace std; int main(){ // enter the number of terms of fibonacci sequence to print int n; cout << "Enter a number: "; cin >> n; // stores the previous value int pre = 0; // stores the current value int cur=1; // loop to print n terms of fibonacci sequence for(int i=1; i<=n; i++){ // prints the current value cout << cur << " "; // stores the current value to temp variable int temp=cur; // changes the current value by adding the prvious value to itself cur = cur + pre; // changes the previous value to temp value pre = temp; } return 0; } |
Output:
1 2 3 4 |
Enter a number: 10 1 1 2 3 5 8 13 21 34 55 |
Printing Fibonacci Sequence using Recursion
Now, we will see how to make this program using Recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include<iostream> using namespace std; // Recursive function to give fibonacci sequence int fib(int n){ if(n < 2){ return n; }else{ return fib(n-2) + fib(n-1); } } int main(){ // enter the number of terms of fibonacci sequence to print int n; cout << "Enter a number: "; cin >> n; int i=1; while(i<=n){ // Printing the fibonacci sequence cout << fib(i) << " "; i++; } return 0; } |
Output:
1 2 3 4 |
Enter a number: 8 1 1 2 3 5 8 13 21 |