Next
While Loop 
Tcl/Tk Tutorial - Create GUI using Tk with Tcl Language
For Loop

The Control Flow Loops

For 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

I like this syntax better...
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

Syntax:
foreach varName list body
This is a loop to make programming more easier. Primarily used for lists. Example...

#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 .lab
The 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
Next
While Loop 

Comments

Kulbhushan at 04 Oct, 2007 03:04
brilliant site...!! Its really helpful for me from school to college....!! thanks for those who is responsible for this site...!! may god bless you all.... Kuchh jayda hi ho gya na.....
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed