top of page

if statement:
 An 'if' statement consists of a Boolean expression followed by one or more statements.
 
if...else statement:
 An 'if' statement can be followed by an optional 'else' statement, which executes when the Boolean expression is false.
 
nested if statements:
 'if' or 'else if' statement inside another 'if' or 'else if' statement(s).
 
switch statement:
A switch statement allows a variable to be tested for equality against a list of values.

while loop:
     Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop:
  Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

nested loops:  
   One or more loop inside any another while, for or do..while loop.

 

Foreach:

   The foreach command implements a loop where the loop variable(s) take on values from one or more lists. 

Statements and Loops

 # 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

 }

# A program to compute the sum of the numbers from 1 to n

 

proc sumto {n} {

    set sum 0

    set i 1

    while {$i <= $n} {

       set sum [expr $sum + $i]

       incr i

    }

    puts "The sum of the numbers from 1 to $n is  $sum "

}

 

puts -nonewline stdout "Enter a number: "

flush stdout

gets stdin n

sumto $n

#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” }

}

#Find the number of elements in the list without using llength
set list "1 2 3 4 5 6 7 8 11 17 33 3 4 8"
set i 0
foreach ele $list {
set b "$ele = $i"
incr i
}
puts $i


 

#TCL Program – count letters in the given string using tcl

set str “LIHAKHDBLICIHJAADFDCSDBBBDFDB”
set l [string length $str]
puts $l
set cnt_A 0
set cnt_B 0
set cnt_C 0
set i 0
while {$i<=$l} {
if {“A”==[string index $str $i]} {
incr cnt_A   } elseif {“B”==[string index $str $i]} {
incr cnt_B   } elseif {“C”==[string index $str $i]} {
incr cnt_C   }
incr i
}

puts “The count of A is $cnt_A \n
The count of B is $cnt_B \n
The count of C is $cnt_C”

© 2015 Thirumurugan

bottom of page