Here is the C++ code to print Fibonacci Series up to nth term . It takes input for n and prints Fibonacci Series up to that number of terms. You all should have in mind how it works exactly. Here is the algorithm.
Steps
User side
1: User asked to enter a number of nth term of Fibonacci Series
2: Screen displays Fibonacci series up to that number of terms.
Developer side
1: Declare variables that are going to be used in program .
2: Input a number for nth term of Fibonacci Series from user.
3: Pass that number to a function named "Fibonacci (int)"
4: In the function start a loop from zero to less the number entered by user.
5: In each iteration check if the number is less than or equal to 1 display it as it is.
6: If the above condition is false do the following
d = c + b;
c = b;
b = d;
7: Display the variable "d"
8: Return control back to main, So program ends here.
Code:
#include<iostream>
using namespace std;
void
Fibonacci(int);
int
main()
{
int x;
cout << "Enter
number of nth term of series of Fibonacci series= ";
cin >> x;
Fibonacci(x);
system("pause");
return 0;
}
void
Fibonacci(int x)
{
int a, b
= 1, c = 0, d = 0;
for (a =
0; a < x; a++)
{
if
(a <= 1)
{
d = a;
}
else
{
d = c + b;
c = b;
b = d;
}
cout << d <<" ";
}
cout<<endl;
}
Output:
Comments
Post a Comment