# Procedure in TCL

There are number of scripts which can be executed more than once, to utilize the reusability we use procedure in TCL.

Syntax:

Proc proc_name {argument} {
Body
}

Eg.

#1.
return [expr \$a + \$b]
}

Now we can use this proc number of times whenever we need to add 2 numbers.

result: 30

result: 15

#2.
proc add {a {b 50}} {
return [expr \$a + \$b]
}

Now this piece of script can be used number of times but whenever two numbers are there it will be added but if only one input will be provided then the input will be added with 50.

Result: 30

result: 60

#3.
proc average {numbers} {
set sum 0;
foreach number \$numbers {
set sum [expr \$sum + \$number]
}
set avg [expr \$sum/[llength \$numbers]]
return \$avg
}

Now use any set of numbers to find out the average of numbers.

puts [avg {2 3 5 6}]

Result: 4

puts [avg {5 7}]

Result: 6

#4.
proc factorial {number} {

if {\$number <= 1} {
return 1
}

return [expr \$number * [factorial [expr \$number-1]]]
}

puts “[factorial 3]”

Result: 6

puts “[factorial 5]”

Result: 120