O'Reilly logo

Practical Programming in Tcl & Tk, Third Edition by Brent B. Welch

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required