TCL Assignment 2
TCL Assignment 2
1. Try out the following command sequence and interpret the output :
set X 100
set Y 256
set Z [expr {$Y + $X}]
set Z_LABEL "$Y plus $X is "
puts "Because of the precedence rules \"5 + -3 * 4\" is: [expr {-3 * 4 + 5}]"
puts "Because of the parentheses \"(5 + -3) * 4\" is: [expr {(5 + -3) * 4}]"
set A 3
set B 4
puts "The hypotenuse of a triangle: [expr {hypot($A,$B)}]"
#
# The trigonometric functions work with radians ...
#
set pi6 [expr {3.1415926/6.0}]
puts "The sine and cosine of pi/6: [expr {sin($pi6)}] [expr {cos($pi6)}]"
#
# Working with arrays
#
set a(1) 10
set a(2) 7
set a(3) 17
set b 2
puts "Sum: [expr {$a(1)+$a($b)}]"
2. Try out the following command sequence and interpret the output
3. Try out the following command sequence and interpret the output :
set x 1
if {$x != 1} {
puts "$x is != 1"
} else {
puts "$x is 1"
}
#
# Be careful, this is just an example
# Usually you should avoid such constructs,
# it is less than clear what is going on and it can be dangerous
#
set y x
if "$$y != 1" {
puts "$$y is != 1"
} else {
puts "$$y is 1"
}
#
# A dangerous example: due to the extra round of substitution,
# the script stops
#
set y {[exit]}
if "$$y != 1" {
puts "$$y is != 1"
} else {
puts "$$y is 1"
}
4. Try out the following command sequence and interpret the output
set x "ONE"
set y 1
set z ONE
switch $x "$z" {
set y1 [expr {$y+1}]
puts "MATCH \$z. $y + $z is $y1"
} ONE {
set y1 [expr {$y+1}]
puts "MATCH ONE. $y + one is $y1"
} TWO {
set y1 [expr {$y+2}]
puts "MATCH TWO. $y + two is $y1"
} THREE {
set y1 [expr {$y+3}]
puts "MATCH THREE. $y + three is $y1"
} default {
puts "$x does not match any of these choices"
}
switch $x "ONE" "puts ONE=1" "TWO" "puts TWO=2" "default" "puts NO_MATCH"
switch $x \
"ONE" "puts ONE=1" \
"TWO" "puts TWO=2" \
"default" "puts NO_MATCH";
5. Try out the following command sequence and interpret the output
set x 1
# The next example shows the difference between ".." and {...}
# How many times does the following loop run? Why does it not
# print on each pass?
set x 0
while "$x < 5" {
set x [expr {$x + 1}]
if {$x > 7} break
if "$x > 3" continue
puts "x is $x"
}
6. Try out the following command sequence and interpret the output
puts "Start"
set i 0
while {$i < 10} {
puts "I inside third loop: $i"
incr i
puts "I after incr: $i"
}
set i 0
incr i
# This is equivalent to:
set i [expr {$i + 1}]
for {set i 0} {$i < 10} {incr i} {
puts "I inside first loop: $i"
}
puts "Start"
set i 0
while {$i < 10} {
puts "I inside third loop: $i"
incr i
puts "I after incr: $i"
}
set i 0
incr i
# This is equivalent to:
set i [expr {$i + 1}]