C programming Problem Write a function that computes the val
C programming
Problem
Write a function that computes the value of the n-th element of the Fibonacci sequence. The function needs to call itself, in order to compute the result, i.e. it works recursively.
Use that function to create a program that asks the user to enter the number of the element of the sequence and that outputs the result on the command line.
Steps to take
Identify and document the input(s) and the output(s)
Describe the algorithm that solves the problem
Write the C program that solves the problem
What to submit
Submit two files :
One word document that contains your take on steps #s 1&2
Step #2 needs to contain a detailed explanation about how your recursive function works. This explanation needs to refer to the recursion step(s) and the base case.
A .c file that contains your C program developed in step #3
Solution
function fibonacci($n) { //0, 1, 1, 2, 3, 5, 8, 13, 21 /*this is an error condition returning -1 is arbitrary - we could return anything we want for this error condition: */ if($n <0) return -1; if ($n == 0) return 0; if($n == 1 || $n == 2) return 1; $int1 = 1; $int2 = 1; $fib = 0; //start from n==3 for($i=1; $i<=$n-2; $i++ ) { $fib = $int1 + $int2; //swap the values out: $int2 = $int1; $int1 = $fib; } return $fib; }
