Fibonacci Numbers

 In Fibonacci Numbers, the next number is the sum of previous two numbers. 

 Here we are going to write a file named fib.tcl and then we will run it as, tclsh fib.tcl 

#fib.tcl

#

proc nthFib {n} {

#Base conditions

if {$n == 1} {

return 0;

} elseif {$n == 2} {

return 1;

} elseif {$n > 2} {

set a 0;

set b 1;

set sum 0;

for {set i 2} {$i != $n} {incr i} {

set sum [expr {$a + $b}];

set a $b;

set b $sum;

}

return $b;

}

}

#Examples

puts "1st number in the fibonacci numbers: [nthFib 1]";

puts "2nd number in the fibonacci numbers: [nthFib 2]";

puts "5th number in the fibonacci numbers: [nthFib 5]";

puts "8th number in the fibonacci numbers: [nthFib 8]";

puts "11th number in the fibonacci numbers: [nthFib 11]";


Happy reading and thank you. Meet you soon.

Comments

Popular posts from this blog

Bash Shell In Linux

Creating An Animation Using A Text Editor

expr command In TCL