Recursive Functions (58)

4 Name: >>2 : 2008-02-12 14:02 ID:1mWr7Jsm

>>3
Try to write the fibonacci algorithm iteratively.
The recursive approach is simple
[code]
/* C */
int fib(int n) {

if(n == 0) return 0;
else if(n == 1) return 1;
else return fib(n-1) + fib(n-2);

}

; scheme
(define (fib n)
(cond ((= n 0) 0)

     (= n 1) 1)
(else (fib (- n 1) (- n 2))))))

[/code]

Figuring out how to write it iteratively is not that easy, try it :D

Also, they are not 'forcing' recursion.
Recursion can be the same with iteration if written properly.
(ie where tail-call optimization is possible)

This thread has been closed. You cannot post in this thread any longer.