Single Post

Header

Sunday, September 30, 2012

TCL Interview Questions and Answers – 2

TCL script examples with sample programs
TCL Program – Check given number is odd or even in tcl
proc oddeven {n} {
if {$n%2==0} {
puts “the given $n is even” } else {
puts “the given number $n is odd” }
}
oddeven 24
oddeven 67
o/p:
the given 24 is even
the given number 67 is odd
TCL Program – remove duplicates in the given list using tcl
set list1 “venkat gopi prashanth mahantesh krishna nagendra venkat krishna”
set l [llength $list1]
set i 0
set result “”
foreach j $list1 {
set arr($i) $j
incr i
}
for {set k 0} {$k<$l} {incr k} {
set n 0
for {set j [expr $k+1]} {$j<$l} {incr j} {
if {$arr($k)==$arr($j)} {
incr n }
}
if {$n==0} {
lappend result $arr($k)
}
}
puts $result
o/p:
gopi prashanth mahantesh nagendra venkat krishna
TCL Program – Remove the list2 elements in list1 using tcl
set list1 ” venkat praveen gopi syed ravi robert  ”
set list2 “gopi ravi ”
foreach i $list2 {
set index 0
foreach j $list1 {
if { $i==$j } {
set list1 [lreplace $list1 $index $index]
}
incr index 1
}
}
puts $list1
o/p:
venkat praveen syed robert
TCL Program – Average of given numbers using args using tcl
proc avg {args} {
set s 0
set count 0
foreach i $args {
incr count
set s [expr {$s+$i}]  }
set avg [expr {$s/$count}]
puts “count is $count and sum is $s and avg is $avg”
return $avg }
puts [avg 23 34 12 67 45]
o/p:
count is 5 and sum is 181 and avg is 36
36

2 comments:

  1. Below method can also be used to remove the duplicates.
    set list1 "venkat gopi prashanth mahantesh krishna nagendra venkat krishna"

    foreach element $list1 {
    set a($element) 1
    puts $a($element)
    }
    puts [array names a]

    ReplyDelete
  2. In the tcl program (the one using lreplace): remove the list2 element from list 1

    It didn't run for me. When I looked onto the logic I found one disparity and felt like telling you.
    One correction is there:
    ...
    set list1 [lreplace $list1 $index $index]
    incr index -1
    ...
    ..

    Just this minor thing..rest of the code is ok.

    ReplyDelete