There are multiple ways to achieve that. Following are the 3
methods to find nth Fibonacci number.
Algorithm: We know that
Fib (n) = fib (n-1) +
fib (n-2)
Our program will stop if one of the following conditions are met:
n = 2 || n = 1
To learn
about Fibonacci numbers and sequence (click the link).
Method – 1: iteratively using for loop
Code
#include<iostream>
#include<conio.h>
using namespace std;
int fib(int n);
int main()
{
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
getch();
return 0;
}
int fib(int n)
{
int u = 0;
int v = 1;
int i, t;
for(i = 2; i <= n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
#include<conio.h>
using namespace std;
int fib(int n);
int main()
{
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
getch();
return 0;
}
int fib(int n)
{
int u = 0;
int v = 1;
int i, t;
for(i = 2; i <= n; i++)
{
t = u + v;
u = v;
v = t;
}
return v;
}
Output
Method – 2: Using recursion
Code
#include<iostream>
#include<conio.h>
using namespace std;
int fib(int n);
int main()
{
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
getch();
return 0;
}
int fib (int n)
{
cout << "Processing fib(" << n << ")... ";
if (n < 3 )
{
cout << "Return 1!\n";
return (1);
}
else
{
cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\n";
return( fib(n-2) + fib(n-1));
}
}
#include<conio.h>
using namespace std;
int fib(int n);
int main()
{
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
getch();
return 0;
}
int fib (int n)
{
cout << "Processing fib(" << n << ")... ";
if (n < 3 )
{
cout << "Return 1!\n";
return (1);
}
else
{
cout << "Call fib(" << n-2 << ") and fib(" << n-1 << ").\n";
return( fib(n-2) + fib(n-1));
}
}
Output
Method – 3: Using recursion
Code
#include<iostream>#include<conio.h>
using namespace std;
int fib(int n);
int main()
{
int n, answer;
cout << "Enter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << "th Fibonacci number\n";
getch();
return 0;
}
int fib(int n)
{
if (n < 2)
return n;
else
return fib(n-1) + fib(n-2);
}
Nice post!!thanks for sharing good post. java vogue have good collection for improve program skill visit Programming Questions And Answers
ReplyDelete