LOOPS in TCL

There are many statements where we need to execute commands till the condition is met, these are called Loops in TCL. Mainly we use FOR, FOREACH and WHILE Loops in VLSI.

Types of Loops

FOR Loop

Format:

for {initialization} {condition} {Increment} {
statements
}

Flow Diagram

for-loop-tcl

Example:

for {set a 5} {$a < 10} {incr $a} {
puts “The value of a is : $a”
}

Result:

The value of a is : 5
The value of a is : 6
The value of a is : 7
The value of a is : 8
The value of a is : 9

WHILE Loop

Format

while {condition} {
Statement
}

Flow Diagram

while-loop-tcl

Example:

set a 5;
while {$a < 10} {
puts “The value of a is : $a”
}

Result:

The value of a is : 5
The value of a is : 6
The value of a is : 7
The value of a is : 8
The value of a is : 9

Infinite Loop

Sometimes few loops can be infinite, these loops are intended sometimes but if not then the runtime of any execution will shoot up. Below is the infinite loop.

while {1} {
puts “This is infinite loop”
}

FOREACH Loop

Whenever we have a collection of objects and we need to have iterations for all the objects then we can use foreach loop.

Syntax:

foreach <object_name> <collection_of_objects> {
Body
}

Example:

set a {1 2 3 4 5}
foreach b $a {
puts “The value is $b”
}

Result:

The value is 1
The value is 2
The value is 3
The value is 4
The value is 5

NESTED Loop

Nested loops are the loops inside a loop. Nested loops can be an if loop inside an if loop or while loop inside a while loop or if loop inside while or while loop inside if loop, so basically it can be any of these. One syntax is as per below.

Syntax:

while {condition} {
for {initialization} {condition} {increment} {
statements
}
statements
}

Loop Control Statements

Sometimes we need to control a loop hence we need to control statement and change its normal sequence.

Break

Let’s understand this with an example.

set a 10;
while {$a < 20} {
puts “The value of a : $a”
incr a;
if {$a>15} {
break
}
}

Result:

The value of a : 10
The value is a : 11
The value is a : 12
The value is a : 13
The value is a : 14
The value is a : 15

 

Continue

Set a 10;
While {$a < 20} {
If {$a == 15} {
Incr a
Continue
}

Puts “The value of a : $a”
Incr a
}

Result:

The value of a : 10
The value of a : 11
The value of a : 12
The value of a : 13
The value of a : 14
The value of a : 15
The value of a : 16
The value of a : 17
The value of a : 18
The value of a : 19

 

2 Comments

  1. Your theory part is very good, but examples having a lot of mistakes, Please try to reactify.

    • Hey Shad,

      Sometimes commands varies from tool to tool. I would recommend you to read practical section there I have explained and asked for debug.

      Thanks

Leave a Reply