top of page

Procedures

 

A procedure is a code block containing a series of commands. Procedures are called functions in many programming languages. It is a good programming practice for procedures to do only one specific task. Procedures bring modularity to programs. The proper use of procedures brings the following advantages:

  • Reducing duplication of code

  • Decomposing complex problems into simpler pieces

  • Improving clarity of the code

  • Reuse of code

  • Information hiding

 

#proc with one arguments
proc Factorial {x} {
set i 1; set product 1
while {$i <= $x} {
set product [expr $product * $i]
incr i
}
return $product
}

#proc with two arguments
 proc gcd {num1 num2} {
    while {[set tmp [expr {$num1%$num2}]]} {
       set num1 $num2
       set num2 $tmp
    }
    return $num2
 }
 
#proc with multiple arguments 
proc sum {args} {
    set s 0
    foreach arg $args {
       incr s $arg
    }
    return $s
}
puts [sum 1 2 3 4]
puts [sum 1 2]
puts [sum 4]

© 2015 Thirumurugan

bottom of page