int main()
{
int n = 1; //the range of Array
cout<<"enter the number of Fibonacci digits: "<<endl;
cin>>n;
int fib[n];
fib[0] = 1;
fib[1] = 1;
for(int i=2; i<=n; i++)
{
fib[i] = fib[i-1] + fib[i-2]; //fibonacci formula
}
for(int i=0; i<=n; i++)
{
cout<<fib[i]<<", "<<endl;
}
return 0;
}
And it works well, untill I set the n variable larger than 45. The 46th position in fibonacci sequence is negative. Is it only my compiler error or is it general. What can be the cause of it?
Do you suggest that I can't use a variable in a array declaration?
Yes. The compiler does, during compilation, create code for the function that reserves stack memory for local (aka automatic) variables. The array is such. The compiler does not know what the user will write.
You do need a dynamically allocated array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <vector>
#include <iostream>
int main() {
size_t n = 1; // unsigned
std::cin >> n;
std::vector<unsignedlonglong> fib( n ); // <- this is dynamic
fib[0] = 1;
fib[1] = 1;
for ( int i=2; i < n; ++i ) { // Look at the end condition, there is no fib[n]
fib[i] = fib[i-1] + fib[i-2];
}
return 0;
}
Fibonacci gets big quite quickly. The built-in types can store only so many digits. Look at the Boost library for "big int" types.
Your current compiler probably supports non-C++-standard feature: variable length arrays.
However, relying on non-standard features has down-sides.
(1) The code might not compile in any other environment.
(2) You don't learn to use the features that the standard language and library do provide.