Statements (Level-Control-Structures)
Two-Way Selection Statements
provides the means of choosing between two or more paths of execution
General Form:
1
2
3
4if control-expression
// then-clause
else
// else-clause- the control expression must be
Booleanin most of the languages - some other languages like
Caccepts numeric
- the control expression must be
Clause Form:
- the then-clause and else-clause can be signle statement or compound statements in most of the languages
- Perl only accepts compound statements
- Python and Ruby: clauses are statement sequences
Nesting Selectors
Dangling else problem
1
2
3
4
5
6
7
8
9
10
11bool condition1 = true;
bool condition2 = false;
string result = "haha";
if(condition1)
if(condition2)
result = "hehe";
else
result = "hoho";
cout << result << endl; // hoho- In C/C++/Java,
elsematches with the nearest previousif
- In C/C++/Java,
In Perl, this is actually enforced
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16$condition1 = true;
$condition2 = false;
$result = "haha";
if($condition1)
{
if($condition2)
{
$result = "hehe";
} }
else
{
$result = "hoho";
}
print $result;In some languages, clauses are statement sequences which are ended by a reserved word
end1
2
3
4
5
6
7
8
9
10
11
12
13condition1 = true
condition2 = false
result = "haha"
if condition1 then
if condition2 then
result = "hehe"
end
else
result = "hoho"
end
print(result)In Python,
1
2
3
4
5
6
7
8
9
10
11condition1 = True
condition2 = False
result = "haha"
if condition1:
if condition2:
result = "hehe"
else:
result = "hoho"
print(result)
Multiple-Way Selection
allow the selection of one of any number of statements or statement groups
Switch statement in C, C++, and Java
- Control expression and case constants can only be integers
defaultclause is for unrepresented values1
2
3
4
5
6
7
8
9
10
11switch (expression) {
case const_expr_1:
statement_1;
break;
...
case const_expr_n:
statement_n;
break;
default:
statement_n+1;
}Placement
switch-casehas no restructions on the placement of the case expression1
2
3
4
5
6
7
8
9
10int x = 37;
switch(x)
default:
if(isPrime(x)) // skip the if statement
case 2: case 3: case 5: case 7: // quick jump
processPrime(x);
else
case 4: case 6: case 8: case 9: case 10:
processComposite(x);
- unconditional branch in C#
- C# allows unconditional branch like
gotoandbreak1
2
3
4
5
6
7
8
9
10
11
12
13
14int value = 0;
int result = 0;
switch(value){
case < 0:
result += 3;
break;
case 0:
result += 5;
goto case 1;
case 1:
result += 7;
break;
default:
}
- C# allows unconditional branch like
Multiple Selector in two-way selectors:
- the connection of two-way selections using
else if1
2
3
4
5
6
7
8int n = 1;
if(n == 1){
cout << "one" << endl;
}else if(n == 2){
cout << "two" << endl;
}else if(n == 3){
cout << "three" << endl;
} but the structure is more look like this (which is not an actual multiple-way selection)
1
2
3
4
5
6
7
8
9
10
11
12int n = 1;
if(n == 1){
cout << "one" << endl;
}else{
if(n == 2){
cout << "two" << endl;
}else{
if(n == 3){
cout << "three" << endl;
}
}
}In Python,
elifis a single special keyword and enables actual multiple-way selection1
2
3
4
5
6
7n = 1
if n == 1:
print("one")
elif n == 2:
print("two")
elif n == 3:
print("three")
- the connection of two-way selections using
- Implementation
- General approach
- multiple conditional branches
- linear search of a simple table of case values
- Optimized approaches
- array
- hash table
- General approach
Counter-Controlled Loops
- has a loop variable, and a means of specifying the initial, condition, and step
C-based language Syntax:
for ([initial] ; [condition] ; [step]) bodythe
[initial],[condition]and[step]can be whole statements or even statement sequences(statement seperated by,)1
2
3for (int i = 0, j = 0; i < 10; i++, j += 2){
cout << "loop " << i << ", " << j << endl;
}It can even has no statements
1
2
3
4
5
6for (;;){ // while(true)
// body
}
for (;A;){ // while(A)
// body
}It is legal for C++ to go back to the loop body using
goto1
2
3
4
5
6
7
8
9
10
11int i = 0;
for (; i < 10; i++) {
print:
cout << "loop " << i << endl;
}
cout << "one more time?" << endl;
char input;
cin >> input;
if (input == 'y') {
goto print;
}
Logic-Driven Loops
the repetition control is based on a Boolean expression
Pretest Loop
- check the loop condition before the first iteration
whileloop1
2
3while (control_expression) {
// ...
}
Posttest Loop
- check the loop condition after the first iteration
do-whileloop1
2
3do {
// ...
} while (control_expression)
It is also legal for C++ to go back to the loop body using
goto
Data-Structure-Based Loops
- the number of elements in a data structure controls loop iteration
call to an iterator function or a callable object that returns the next element in some chosen order, if there is one; else loop is terminated
Implement using pointer in C
1
2
3for (node* p=root; p!=NULL; traverse(p)){
// use *p to access the current element
}Standard Template Library in C++
- instead of dealing with pointer, STL iterators can simply using the deference operator
*and increment operators++1
2
3for (vector<int>::iterator p=v.begin(); p!=v.end(); p++) {
// use *p to access the current element
}
- instead of dealing with pointer, STL iterators can simply using the deference operator
Java Implementation
the class that implements the Iterable interface (
ArrayList)1
2
3for (String myElement : myList){
// ...
}forEachmethod1
2
3myList.forEach((n) -> {
// ...
});
Python Implementation
The loop variable takes on the values specified in the given sequence
1
2for loop_variable in sequence:
# loop_bodyelse clause is execute if the loop terminates normally
1
2
3
4
5
6
7
8
9pets = ["kitty", "doggy", "pig"]
for pet in pets:
if pet == "piggy":
print("piggy is found!")
break
else: # if the loop terminates normally
print("no piggy")similate counter-controlled loop
1
2for i in range(10):
print(i)
User-Located Loop Control Mechanisms
unconditional unlabeled exits (
breakin most of the languages,lastin Perl)- exit the loop
unlabeled control statement (
continue)- skips the the remainder of the current iteration, but does not exit the loop
Labeled exits
- consider the
breakcan only exist for the current loop but cannot exit the outer loop - we can label the outer loop and then use
break label;to exit the outer loop1
2
3
4
5
6
7
8
9outerLoop:
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
if(i + j == 5){
System.out.println(i + " " + j);
break outerLoop;
}
}
} - If
gotois legal, then simply usegototo exit the outer loop
- consider the


