Fibonacci sequence using dynamic allocation

Hey there! The assignment is the the Fibonacci sequence except the user has to input how many elements they'd like to run for. We have to dynmically allocate memory this time, and build the array around it.

This is what I have so far, it seems to work but when I input large numbers the code starts returning negative numbers and going crazy....


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int main(){
	unsigned int n;

cout << "please input the number of elements you would like this fibonacci sequence to run"<<endl;
cin>>n;
cout<<endl<<endl;

	int* fib = new int[n]; 
	for(int i=2; i<n; i++)
	{
		fib[0]=0;
		fib[1]=1;
		fib[i]=fib[i-1]+fib[i-2];
	}
	
       
        for(int i = 0; i < n; i++) cout << fib[i] << ' ';

        delete[] fib;
		system ("pause");
		return 0;
}




See http://www.ideone.com/8MN2v . I ran it there with input = 20 elements and seems to work OK. How large is large for you? Also note that I corrected the code a bit: Lines 14 and 15 were taken out of the loop.
I think thats because int can only hold a number of 4bytes (about 2,000,000,000). You can try unsigned long instead if that helps.
Ok ok thanks
Last edited on
But which variable would you change to long? cuz there are some that dont let me change them

int* fib = new int[n]; like this one
Topic archived. No new replies allowed.