Fibonacci function using C programming
The Fibonacci series
0, 1, 1, 2, 3, 5, 8, 13, 21, …
begins with the terms 0 and 1 and has the property that each succeeding term is the sum of the two
preceding terms. a) Write a nonrecursive function fibonacci(n) that calculates the nth Fibonacci
number. b) Determine the largest Fibonacci number that can be printed on your system. Modify
the program of part a) to use double instead of int to calculate and return Fibonacci numbers. Let
the program loop until it fails because of an excessively high value.
Answer:
#include <stdio.h> #define MAX 93 unsigned long long int fibonacci( unsigned int n ); int main() { int loop; // loop counter // calculate and display Fibonacci value for 0 to MAX for ( loop = 0; loop <= MAX; ++loop ) { printf( "fibonacci( %u ) = %llu\n", loop, fibonacci( loop ) ); } // end for } // end main // fibonacci nonrecursively calculates nth Fibonacci number unsigned long long int fibonacci( unsigned int n ) { unsigned int j; // loop counter unsigned long long int fib1 = 0; // variable that holds a fibonacci number unsigned long long int fib2 = 1; // variable that holds a fibonacci number // loop to find nth Fibonacci value for ( j = 2; j <= n; ++j ) { if ( j % 2 == 0 ) fib1 += fib2; else fib2 += fib1; } // end for // return nth Fibonacci value if ( n % 2 == 0 ) return fib1; else return fib2; }
Leave a reply