Q:

The Fibonacci numbers is a sequence of numbers Fi:

0

The Fibonacci numbers is a sequence of numbers Fi: 0 1 1 2 3 5 8 13 21 34 … where F0 is 0, F1 is 1, F2 is 1, F3 is 2, and so on. A recursive definition is: F0 = 0 F1 = 1 Fn = Fn-2 + Fn-1 if n > 1 Write a recursive function to implement this definition. The function will receive one integer argument n, and it will return one integer value that is the nth Fibonacci number. Note that in this definition there is one general case but two base cases. Then, test the function by printing the first 20 Fibonacci numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

fib.m

function outval = fib(n)

% Recursively calculates the nth Fibonacci number

% Format of call: fib(n)

% Returns the nth Fibonacci number

if n == 0

 outval = 0;

elseif n == 1

 outval = 1;

else

 outval = fib(n-2) + fib(n-1);

end

end

>> for i = 1:20

 fprintf('%d\n', fib(i))

end

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now