write a code to find fibonacci number in tcl
- User
write a code to find fibonacci number in tcl
- Assistant
To find a Fibonacci number in Tcl, you can use a simple recursive function or an iterative method. Recursion is more straightforward to write but can be less efficient for large numbers due to its time complexity. The iterative method is more efficient, especially for big numbers. Here, I'll demonstrate both methods.
1. Recursive Approach
proc fib_recursive {n} { if {$n <= 1} { return $n } else { return [expr {[fib_recursive [expr {$n - 1}]] + [fib_recursive [expr {$n - 2}]]}] } } # Example usage: to find the 10th Fibonacci number set n 10 puts "Fibonacci number at position $n: [fib_recursive $n]"2. Iterative Approach
proc fib_iterative {n} { if {$n <= 1} { return $n } set a 0 set b 1 for {set i 2} {$i <= $n} {incr i} { set c [expr {$a + $b}] set a $b set b $c } return $b } # Example usage: to find the 10th Fibonacci number set n 10 puts "Fibonacci number at position $n: [fib_iterative $n]"