Write a TCL proc to find the factorial of a number where the number is passed as an argument.
Question
Write a TCL proc to find the factorial of a number where the number is passed as an argument.
Solution
Sure, here is a simple TCL procedure to calculate the factorial of a number:
proc factorial {n} {
if {$n == 0} {
return 1
} else {
return [expr {$n * [factorial [expr {$n-1}]]}]
}
}
Here's how it works:
-
The
prockeyword is used to define a new procedure namedfactorial. This procedure takes one argument,n, which is the number we want to find the factorial of. -
Inside the procedure, we use an
ifstatement to check ifnis equal to 0. If it is, we return 1, because the factorial of 0 is 1. -
If
nis not equal to 0, we use theexprcommand to calculate the factorial. We multiplynby the factorial ofn-1, which we find by recursively calling thefactorialprocedure. -
The result of this calculation is then returned as the result of the
factorialprocedure.
You can call this procedure with a number to find its factorial. For example, factorial 5 will return 120.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.