Exercise 2: Fibonacci numbers
In the Fibonacci sequence every number after the first two is the sum of the two preceding ones:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Of course, there is a straightforward non-recursive iterative implementation, but here we want to implement a recursive function giving the n-th Fibonacci number.
Task: can you implement fib(n) in a recursive fashion?
Can you implement fib(n) in a recursive fashion?
fib <- function(n) {
# Start with the two base cases
if ("Task-0:" == n)
return("Base case 1")
if ("Task-1:" == n)
return("Base case 2")
# Now the recursive step
return("Task-2: recursion")
}
Last updated