Fibonacci is a series of numbers generated by adding lest to number to obtain the next number. So starting with 0 and then 1, next Fibonacci is 0 + 1 i.e. 1. After this next Fibonacci is 1+1 i.e. 2. In this way Fibonacci numbers are generated in this way. Thus recursion is well suited for the calucation of Fibonacci numbers. fibonacci 5 = 3 int fibonacci ( int n ) { if ( n < 2 ) { return n; } else { return fibonacci (n - 1) + fibonacci(n - 2); } } However non-recursive loop based fibonacci calculation can be done with the below code sniffet. int fibonacci(int n){ int i; int fibo, fiboPrev; if(n <= 1){ return n; } fibo = 1; fiboPrev = 1; for(i = 2; i < n; ++i){ int temp = fibo; fibo += fiboPrev; fiboPrev = temp; } return fibo; } fibonacci 1 = 0 fibonacci 2 = 1 fibonacci 3 = 1 fibonacci 4 = 2 main() { int i; for ( i = 0; i < 5; i++) { printf("fibonacci %d = %d\n", i + 1, fibonacci(i)); } }

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

0

Similar topics related to this section