A Factorial Example

To reinforce what we have learned so far, below is a longer example that uses a while loop to compute the factorial function:

Example 1-13 A while loop to compute factorial.
proc Factorial {x} {
   set i 1; set product 1
   while {$i <= $x} {
      set product [expr $product * $i]
      incr i
   }
   return $product
}
Factorial 10
=> 3628800
					

The semicolon is used on the first line to remind you that it is a command terminator just like the newline character. The while loop is used to multiply all the numbers from one up to the value of x. The first argument to while is a boolean expression, and its second argument is a command body to execute. The while/ command and other control structures are described in Chapter 6.

The same math expression ...

Get Practical Programming in Tcl & Tk, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.