Aim: TCL script to find the factorial of a number
Source Code:
set fact 1
for {set i 0} {$i <= 10} {incr i} {
puts "$i! = $fact"
set fact [expr {$fact * ($i + 1)}]
}
Output:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
12)Write a TCL script that multiplies the numbers from 1 to 10
Aim: TCL script that multiplies the numbers from 1 to 10
Source Code:
# A program that does a loop and prints
# the numbers from 1 to 10
#
set n 10
for {set i 1} {$i <= $n} {incr i} {
puts $i
}
Output:
13)Write a TCL script for Sorting a list using a comparison function
Aim: TCL script for Sorting a list using a comparison function
Source Code:
proc compare { mylist } {
set len [llength $mylist]
set len [expr $len-1]
for {set i 0} {$i<$len} {incr i} {
for {set j 0} {$j<[expr $len-$i]} {incr j} {
if { [lindex $mylist $j] > [lindex $mylist [expr $j+1]]} {
set temp [lindex $mylist $j]
lset mylist $j [lindex $mylist [expr $j+1]]
lset mylist [expr $j+1] $temp
}
}
}
puts $mylist
}
set mylist { 7 3 5 2 }
compare $mylist
Output:
2 3 5 7
14 Write a TCL script to (i)create a list (ii) append elements to the list (iii)Traverse the list
(iv)Concatenate the list
Create a list
Syntax:
set listName { item1 item2 item3 .. itemn }
# or
set listName [list item1 item2 item3]
# or
set listName [split "items separated by a character" split_character]
Source code:
#!/usr/bin/tclsh
set colorList1 {red green blue}
set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" _]
puts $colorList1
puts $colorList2
puts $colorList3
Output:
red green blue
red green blue
red green blue
2) append elements to the list
Syntax:
append listName split_character value
# or
lappend listName value
Source Code:
#!/usr/bin/tclsh
set var orange
append var " " "blue"
lappend var "red"
lappend var "green"
puts $var
Output:
orange blue red green
(iii)Traverse the list and (iv)Concatenate the list
Source Code:
set L1 {1 2 3 }
puts $L1
lappend L1 4 5
puts "After append $L1"
puts "Traversing list"
set i 0
set len [llength $L1]
while {$i<$len} {
puts [lindex $L1 $i]
incr i
}
set L2 {-1 0}
puts "List 2 $L2"
set L3 [concat $L2 $L1]
puts "After concat $L3"
Output:
Output:
1 2 3
After append 1 2 3 4 5
Traversing list
1
2
3
4
5
List 2 -1 0
After concat -1 0 1 2 3 4 5
15) Write a TCL script to comparing the file modified times.
Source Code:
proc newer { file1 file2 } {
if ![file exists $file2] {
return 1
} else {
# Assume file1 exists
expr [file mtime $file1] > [file mtime $file2]
}
}
Output:
16) Write a TCL script to Copy a file and translate to native format.
Source Code:
proc File_Copy {src dest} {
set in [open $src]
set out [open $dest w]
puts -nonewline $out [read $in]
close $out ; close $in
}
Output: