STATEMENT-LEVEL CONTROL STUCTURES
Control structure is a control statement and the statement whose execution it controls.
Selection statements, provide the means of choosing between two or more path of execution.
There are two general categories :
- Two-way selector
Example: if-else
General form : if control_expresion
Then clause
Else clause
We can also make nesting selectors , to be clear look at the example.
Example of nesting selector :
If(sum == 0 ){
If(count == 0 )
Result = 0;
}
Else result = 1;
- Multiple way selector
Allow the selection of one of any number of statement in statement groups.
For example: if-else if , C’s switch case(in C’s switch case the control expression can be only an integer type).
Example of using C,C++, Java, and JavaScript switch case ;
Switch(expression) {
Case cons_exprt1: stmt1;
Case cons_exprt2: stmt2;
Default: stmt(n+1)
}
Example of multiple-way selection using if :
If coutn < 10 :
Bag1 = True
Elif count < 100 :
Bag2 = True
Elif count < 1000 :
Bag3 = True
The Python example can be written as a Ruby case
case
when count < 10 then bag1 = true
when count < 100 then bag2 = true
when count < 1000 then bag3 = true
end
Iterative statements, repeated execution of a statement or compound statement is accomplished either by iteration or recurtion.
Counter-controlled loops, counting iterative statement has a loop variable and a means of specifying the initial and terminal, and stepsize values.
Example: for ,, for ([expr_1] ; [expr_2] ; [expr_3]) statement
Logically controlled loops, the repetition control based on a Boolean expretion.
It can be pretest or posttest. Pretest is testing the statement first before returning the value. Posttest is return the value first then test. Example of pretest is while . example of posttest is do-while.
User-controlled loop control mechanism, example in C there are break to stop a loop and continue to skip the remainder of the current iteration but does not exit the loop.
Iteration based on data structures
- The number of elements in a data structure controls loop iteration
- Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate
- C’s for can be used to build a user-defined iterator:
for (p=root; p==NULL; traverse(p)){
…
}