Previous Control Flow - If |
Tcl/Tk Tutorial For Loop |
Next While Loop |
The most commonly used loop - the for loop. This is extremely useful when you have to execute a given set of instruction a limited number of times with little or no changes.
Syntax:for init test next body
for { init } { test } { next } {
body
}
Now, for the first time we write a script to do something useful - make a multiplication table. Wondering how that is useful? You will find it very useful when you have forgotten mathematics - like me.
#Multiplication table... set n 4 ;# We want the multiplication table of 4 set table "" for { set i 1 } { $i <= 10 } { incr i } { # This will append all multiples of all numbers for the number n # into a variable called table set table "$table $i x $n = [expr $i \* $n]\n" } label .mul -text "Multiplication table for $n\n\n$table" pack .mul
foreach varName list body
#Make the list set list [list "Item 1" {Item 2} Last] set text "" foreach item $list { #Append the every item to $text set text "$text\n$item" } #Shows the result label .lab -text "$text" pack .labThe same can be achieved by a regular for loop like this.
#Make the list set list [list "Item 1" {Item 2} Last] set text "" for { set i 0 } { $i <= [llength $list] } { incr i } { #Append the every item to $text set text "$text\n[lindex $list $i]" } label .lab -text "$text" pack .lab
Previous Control Flow - If |
Contents | Next While Loop |