I want some one to explain Fibonacci series logic in c++..
For a Beginner its a difficult to get it completely..
Here is a one method of explain to find Fibonacci series. I Think It Is Well Explanation..
#include <iostream>
usingnamespace std;
int main()
{
cout << "How many terms do you want to find?" << endl;
int Fibonacci;
cin >> Fibonacci;
int FibTerms[Fibonacci]; // initializes an array with the number of elements requested.
if (Fibonacci>=1)
{
FibTerms[0]=1;
cout << FibTerms[0] << " ";
}
if (Fibonacci>=2)
{
FibTerms[1]=1;
cout << FibTerms[1] << " ";
}
if (Fibonacci>=3)
{
for (int i=2; i<Fibonacci; i++) // we have already made the first 2 terms
{
FibTerms[i]=FibTerms[i-1]+FibTerms[i-2];//adds the previous 2 terms.
cout << FibTerms[i] << " ";
}
}
cin.clear();
cin.ignore(255, '\n');
cin.get();
}
Only change I made between posting and that screenshot was change the array to type long long so you can have more terms before it hits the number cap.
compilers dont usually allow that manga. manudude is the first ive seen to do that. everyone else uses a stl container or dynamic array. dont do what manga did because 99/100 it wont work
// Fibonacci Sequence.cpp : main project file.
#include <iostream>
usingnamespace std;
int main()
{
cout << "How many terms do you want to find?" << endl;
int Fib;
cin >> Fib;
constint Fibonacci = Fib;
int* FibTerms = newint[Fibonacci]; // initializes an array with the number of elements requested.
if (Fibonacci>=1)
{
FibTerms[0]=1;
cout << FibTerms[0] << " ";
}
if (Fibonacci>=2)
{
FibTerms[1]=1;
cout << FibTerms[1] << " ";
}
if (Fibonacci>=3)
{
for (int i=2; i<Fibonacci; i++) // we have already made the first 2 terms
{
FibTerms[i]=FibTerms[i-1]+FibTerms[i-2];//adds the previous 2 terms.
cout << FibTerms[i] << " ";
}
}
delete [] FibTerms;
cin.clear();
cin.ignore(255, '\n');
cin.get();
}
You can't set a constant to a variable value in VC++.
That's why you just do this:
1 2 3 4 5 6 7 8 9 10 11 12
cin >> Fibonacci;
std::vector<int> FibTerms;
FibTerms.reserve(Fibonacci);
for(int f = 0; f < Fibonacci; f++)
{
int temp;
FibTerms.push_back(temp);
}
//And then continue on with the rest of your program.
There is no reason to use an array or vector at all for this.
The standard requires that array sizes are compile time constants. Compilers that allow VLAs in C++ code do so though an extension that can be disabled so that the compiler is conforming.