Download this source file
/* FibFunc.c - Calculate the n-th Fibonacci number.
* This program asks for the number of months that a single
* pair of rabbits and their progeny will breed for,
* where each month every pair older than 1 month will
* reproduce 1 new pair of rabbits. This value is the
* n-th Fibonacci number. This version uses a function.
* Written by Wayne Pollock, 2001.
*/
#include
unsigned long fib ( unsigned int n );
int main ( void )
{ int n;
printf ( "For how many months do the rabbits breed: " );
if ( scanf( "%i", &n ) != 1 )
{ fprintf( stderr, "***ERROR: Bad input!\a\n" );
return -1;
}
if ( n < 0 )
{ fprintf( stderr, "***ERROR: Input must be a number >= zero!\a\n" );
return -1;
}
printf ( "The number of pairs of rabbits after %i months is %lu.\n",
n, fib(n) );
return 0;
}
unsigned long fib ( unsigned int n )
{ unsigned int i;
unsigned long prev = 0, result = 1, next;
for ( i = 1; i <= n; ++i )
{
next = prev + result;
prev = result;
result = next;
}
return result;
}
/*
=====================Output of Fib1.c follows======================
For how many months do the rabbits breed: 12
The number of pairs of rabbits after 12 months is 233.
*/