Ok, I got it to work using a pointer. Here's my code.
#include <ctime>
#include <iostream>
using namespace std ;
int fib ( int ) ;
int main ( )
{
clock_t start ;
clock_t end ;
cout << "Beginning timer..." << endl ;
start = clock() ;
cout << endl ;
for ( int k = 0 ; k < 12 ; k++ )
{
int i = fib ( k ) ;
cout << i << "\t" ;
}
cout << endl ;
end = clock() ;
cout << "\nThe calculation took " << ( double ( end ) - start ) / CLOCKS_PER_SEC << " seconds.\n" ;
cout << "\n\n-- Done --\n\n" ;
return 0 ;
}
int fib ( int n )
{
int * fibArray = new int[ n ] ;
if ( n <= 1 )
return 1 ;
else
{
fibArray[ 0 ] = 1 ;
fibArray[ 1 ] = 1 ;
for ( int i = 2 ; i <= n ; i++ )
fibArray [ i ] = ( fib ( n - 1 ) + ( fib ( n - 2 ) ) ) ;
}
return fibArray[ n ] ;
}
I can't get it to work with numbers >=12; it gives a system error that it failed unexpectedly. I'm guessing it's a stack issue, but is there a way around it? Is my program the best it can be (using recursion and arrays)?
Last edited by Duki; Oct 25th, 2007 at 1:44 am.
It is practically impossible to teach good programming style to students that have had prior exposure to Basic; as potential programmers they are mentally mutilated beyond hope of regeneration.
-Edsger Dijkstra