Sunday, December 6, 2015

Control Structures

Control Structures : (Under construction)

In general execution of the program would be sequential, if the programmer needs to change the flow of execution, he can very well do using certain tcl constructs. We will discuss about them in this section. Following are the different constructs which are available in TCL:

  • if - else & if - elseif - else structure
  • while structure
  • foreach  structure
  • for structure
  • switch





  • if - else & if - elseif - else structure
     If the condition is evaluated true, command1 and command2 will be executed.
     Syntax :
       if { condition } {
       command1
       command2
       }


     You can use if-else structure as well. i.e. if the condition is true do this and if it is false do that.
    Syntax :
     if { condition } {
       command1
       command2
      } else {
        command3
        command4
     }

You can use if-elseif-else and even nested if within each group.

If condition1 is evaluated to true, command_m would be executed, else if condition2 is evaluated to true command_n. If neither the condition evaluates to true, command_p would be executed



   if { condition1 } {
  command_m  
 } elseif { condition2 } { 
  command_n    
} else {  
command_p  
  }
Example 1:



While loop :

  • While the condition evaluates to true iterate over the loop again and again till it evaluates to false. Once it evaluates to false come out of the loop.



while { condition } {
statement1;statement2;updation; }


Example 2:


For loop :
It is similar to the while loop except that you can have a flexibility to  initialize the loop iterator and also update the iterator in the same line.


for { initiliaze } { condition } { updation } {
command1;command2;..}

Example 3:


foreach control structure:
It loops over a set of variables in the list and executes operations on each variable. It is the most commonly used control structure in the TCL.


foreach var <list> {

execute operation on var;
statement1;
statement2;
.
.
}

Example 4:


Switch :
"switch" is similar to if - elseif - else structure, but it switches to  and executes the first encountered and first satisfied pattern condition. It provides the compact and readable coding structure.
Syntax:
  switch ?options? string pattern body ?pattern body? ...
where,
options - type of matching could be specified here. Values
          could be "exact", "glob" or "regex" type.
string - value to be tested...variable to be switched on.
pattern - body - These are specified in pairs.
The variable value is tested with various patterns. The body of whichever pattern matches is executed.


Example 5 :



No comments: