I did not know that OP was looking for a Fibonacci sequence. I
just did it this way:
/* a program to print the sum of last 2 numbers.
Which is the definition of a Fibonacci sequence.
The "classical" implementation is:
int
fib( int n )
{
return n <= 0 ? 1 : fib( n - 1 ) + fib( n - 2 ) ;
}
It's sometimes used as a good example of when not to use
recursion
; if you just want a few specific values, and add a
cache, however, it's not that bad:
int
fib( int n )
{
static std::vector< int > cache( 2, 1 ) ;
if ( n >= static_cast< int >( cache.size() ) ) {
cache.push_back( fib( n - 1 ) + fib( n - 2 ) ) ;
}
return n < 0 ? 1 : cache[ n ] ;
}
Both such solutions suffer from the fact that int's overflow for
very small values of n, however. My solution above doesn't.
and it prints fine, except that it puts a comma at the end
Which is a separate (and general) problem: how to format
sequences of data.
and I have out a limit of 10 numbers:
Try outputting 100 values, and see what happens.