Learn TCL with Real Code Examples
Updated Nov 20, 2025
Code Sample Descriptions
1
Tcl Counter and Theme Toggle
set count 0
set isDark 0
proc updateUI {} {
global count isDark
puts "Counter: $count"
puts "Theme: [expr {$isDark ? \"Dark\" : \"Light\"}]"
}
proc increment {} {
global count
incr count
updateUI
}
proc decrement {} {
global count
incr count -1
updateUI
}
proc reset {} {
global count
set count 0
updateUI
}
proc toggleTheme {} {
global isDark
set isDark [expr {1 - $isDark}]
updateUI
}
# Simulate actions
updateUI
increment
increment
toggleTheme
decrement
reset
Demonstrates a simple counter with theme toggling using Tcl variables and console output.
2
Tcl Simple Addition
set a 10
set b 20
set sum [expr {$a + $b}]
puts "Sum: $sum"
Adds two numbers and prints the result.
3
Tcl Factorial
set fact 1
for {set i 1} {$i <= 5} {incr i} {
set fact [expr {$fact * $i}]
}
puts "Factorial: $fact"
Calculates factorial of 5 using a loop.
4
Tcl Fibonacci Sequence
set fib0 0
set fib1 1
puts $fib0
puts $fib1
for {set i 3} {$i <= 10} {incr i} {
set next [expr {$fib0 + $fib1}]
puts $next
set fib0 $fib1
set fib1 $next
}
Generates first 10 Fibonacci numbers.
5
Tcl Max of Two Numbers
set a 15
set b 25
if {$a > $b} {
set max $a
} else {
set max $b
}
puts "Max: $max"
Finds the maximum of two numbers.
6
Tcl Array Sum
set nums {1 2 3 4 5}
set sum 0
foreach n $nums {
set sum [expr {$sum + $n}]
}
puts "Sum: $sum"
Sums elements of an array.
7
Tcl Even Numbers Filter
set nums {1 2 3 4 5}
foreach n $nums {
if {[expr {$n % 2}] == 0} {
puts "Even: $n"
}
}
Prints even numbers from an array.
8
Tcl Conditional Counter Increment
set count 3
if {$count < 5} {
incr count
}
puts "Count: $count"
Increment counter only if less than 5.
9
Tcl Resettable Counter
set count 0
incr count
incr count
incr count
puts "Count: $count"
set count 0
puts "Count after reset: $count"
Counter that increments and can be reset.
10
Tcl Theme Toggle Only
set isDark 0
puts "Theme: [expr {$isDark ? \"Dark\" : \"Light\"}]"
set isDark [expr {1 - $isDark}]
puts "Theme: [expr {$isDark ? \"Dark\" : \"Light\"}]"
set isDark [expr {1 - $isDark}]
puts "Theme: [expr {$isDark ? \"Dark\" : \"Light\"}]"
Toggles theme multiple times.