Updated: 18 October 2026. Added trace a Tcl loop with an accumulator. Original publication date retained.

Copyable Tcl examples and corrections

Updated 14 October 2026. This lesson uses Tcl, the language; it does not require a Tk graphical interface. The examples below were checked with Tcl 9.0.4. The original exercise screenshots remain below for reference.

1. Swap characters without replacing them twice

This maps a to b and b to a in one pass. Replacement text is not scanned again. Result: baab.

string map {a b b a} "abba"

2. Variable and command substitution

Double quotes allow the variable and bracketed command to be evaluated. Braces preserve them as literal text at this parsing step. Here expanded becomes Ada has 3 letters; literal contains the dollar sign and brackets unchanged.

set name Ada
set expanded "$name has [string length $name] letters"
set literal {$name has [string length $name] letters}
list $expanded $literal

3. Average ten numbers

The answer for 1 through 10 is 5.5. Initializing the total to 0.0 makes this a floating-point calculation. Use llength, not length, to count list elements. The procedure also rejects an empty list; nonnumeric input raises an arithmetic error.

proc average {numbers} {
    set count [llength $numbers]
    if {$count == 0} {error "average needs at least one number"}
    set total 0.0
    foreach number $numbers {
        set total [expr {$total + $number}]
    }
    return [expr {$total / $count}]
}
average {1 2 3 4 5 6 7 8 9 10}

4. Sum the even numbers from 0 through 10

The result is 30. The remainder test selects even integers.

set total 0
foreach n {0 1 2 3 4 5 6 7 8 9 10} {
    if {$n % 2 == 0} {set total [expr {$total + $n}]}
}
set total

5. Display a number in different bases

This prints binary=1111 decimal=15 hex=f octal=17. Formatting changes the representation. To enter octal 17 explicitly, expr {0o17} evaluates to decimal 15.

format "binary=%b decimal=%d hex=%x octal=%o" 15 15 15 15

References: official Tcl documentation for string map, expressions and arithmetic and format conversions. These links document Tcl 8.6; the execution check above used 9.0.4.

Original exercise notes and screenshots

 1. Write Tcl script to swap a set of character in two string [5]

Given: Two strings.

Task: To swap the set of characters in to strings.

Command used: string map

 

# s and t are variable having string in them.

Tcl terminal examples using string map to replace parts of a string.

2. Discuss variable substitution and command substitution in your words [5]

Command substitution.

If a word contains an open bracket (``['') then Tcl performs command substitution. To do this it invokes the Tcl interpreter recursively to process the characters following the open bracket as a Tcl script. The script may contain any number of commands and must be terminated by a close bracket (``]''). The result of the script (i.e. the result of its last command) is substituted into the word in place of the brackets and all of the characters between them. There may be any number of command substitutions in a single word. Command substitution is not performed on words enclosed in braces.

  Tcl string length example returning 22 characters for 'This is my test string'.

Variable substitution.

If a word contains a dollar-sign (``$'') followed by one of the forms described below, then Tcl performs variable substitution: the dollar-sign and the following characters are replaced in the word by the value of a variable. Variable substitution may take any of the following forms:

$name

Name is the name of a scalar variable; the name is a sequence of one or more characters that are a letter, digit, underscore, or namespace separators (two or more colons).

 $name(index)

Name gives the name of an array variable and index gives the name of an element within that array. Name must contain only letters, digits, underscores, and namespace separators, and may be an empty string. Command substitutions, variable substitutions, and backslash substitutions are performed on the characters of index.

 ${name}

Name is the name of a scalar variable. It may contain any characters whatsoever except for close braces.

There may be any number of variable substitutions in a single word. Variable substitution is not performed on words enclosed in braces.

 Tcl terminal assigning aValue to variable v and printing its value.

3.Write Tcl script to find average of 10 numbers with procedure [5]

# proc: Define a Tcl procedure.

# puts: Output a string to an I/O stream.

# foreach:  Loop construct over a list of values.

# expr: Evaluate a math expression.

# llength: Return the number of elements in a list.

Tcl procedure computing the arithmetic mean of a list; the examples return 49.0 and 58.

4. Write Tcl script to sum only even number between 0-10 using foreach command [5]

# if: Conditional command. Allows else and elseif clauses.

# return: Return a value from a procedure.

 Tcl procedure adding the even numbers from 1 to 10 and returning 30.

5. Write Tcl script for conversion of following with usage of format or/and procedure [10]

(a) a decimal number to other number system

(b) an octal number to other number system

# format: Format a string similar to C sprintf.

# %b- binary, %d – decimal, %x – hexa decimal , %o – octal conversion.

Tcl format examples displaying 15 as binary 1111, hexadecimal f, decimal 15 and octal 17.

Trace a Tcl loop with an accumulator

Try this small Tcl example: set total 0; foreach value {2 4 6} {incr total $value}; set total. The resulting value is 12. Starting from zero, the body runs once for each list element and adds that value to the accumulator. The official foreach reference describes the iteration rules; this is an original simple exercise.

Change the list to empty and explain why the result stays zero. Then change one element and predict the new total before running it. Keeping initialization, iteration and final value separate makes the code easier to reason about than memorizing a screenshot. No Tk graphical interface is needed for this language example.