C++ Program to Find the Fibonacci Sequence

Last updated on:

In this tutorial, we will learn about the Fibonacci sequence in C++ i.e. how to write a program to find Fibonacci sequence using C++.

Quick Info:💡

↪ The Fibonacci sequence is a series where the next term is the sum of previous two terms.

↪ For example, if two terms are 0&1 then, the fibonacci sequence can be as: 0, 1, 1, 2, 3, 5, 8, 13, 21….

↪ Here, we will find the fibonacci series upto certain number to display its output on the output console.

Fibonacci series of a number can be performed in two ways:

  • Without Recursion
  • With Recursion

Fibonacci Sequence Without Recursion

Fibonacci sequence without recursion is a simple program to find it.

Simply, the user will be asked to enter a positive integer then, the Fibonacci sequence is computed and displayed to a user.

Example:

#include<iostream.h>
#include<conio.h>
void main(){
int fibo=1, first_number, second_number;
cout<<"enter the first number:=";
cin>>first_number;
cout<<"enter the second number:=";
cin>>second_number;
while(fibo<=5)
{
fibo=first_number+second_number;
first_number=second_number;
second_number=fibo;
cout<<fibo<<"\t";
}
getch();
}
//Output:
enter the first number:=0
enter the second number:=1
1 2 3 5 8
Fibonacci

Working:

fibo_simple

Fibonacci Sequence With Recursion

Recursion (Recursive function) is defined as – the function calls itself repeatedly unless the code included in the body gets terminated.

And, this is a program to find fibonacci series using recursion.

Note: Always remember that execution starts from the main body only.

Example:

#include<iostream.h>
#include<conio.h>
int fibo(int n)
{
if((n==0)||(n==1))
return 1;
else
fibo(n-1)+fibo(n-2);
}
void main(){
int n;
cout<<"enter the value of n:=";
cin>>n;
cout<<"fibonacci sequence is:\n";
cout<<fibo(n)<<endl;
getch();
}
//Output:
enter the value of n:=5
fibonacci sequence is:
8
Fibonacci_r

Working:

fibo_recursion

Note: Due to recursion, for each function call, an entry is first created in the stack frame and are then executed in a LIFO manner(i.e. Last In First Out).

Want more programs on recursion?

Just Visit: Factorial,

Well, I hope it really helped you to know C++ better.

Attention reader⚠ Don’t stop learning now.

Just stay with us to get more such exciting codes to explore more in C++.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *