PROGRAMMING LANGUAGES
STATEMENT-LEVEL CONTROL
STRUCTURES
1
Introduction
A control structure is a control statement and the statements whose
execution it controls
– Selection Statements
– Iterative Statements
There is only one design issue that is relevant to all of the selection and
iteration control statements:
– Should a control structure have multiple entries?
Statement-Level Control Structures
In programming, "multiple entries" in control structures typically refers to the ability of a control structure (like
loops or conditional statements) to handle multiple conditions or cases.
Pros
1. Flexibility: Allowing multiple entries can make a control structure more flexible, enabling it to handle various
conditions or states without needing to restructure the code significantly.
2. Efficiency: In some cases, multiple entries can lead to more efficient code execution by allowing the program to
bypass unnecessary checks or operations.
Cons of Multiple Entries
1. Complexity: Multiple entry points can lead to increased complexity in understanding the flow of
control. It may become harder for developers to follow the logic, especially in larger codebases.
2. Readability: Code readability can suffer when there are multiple ways to enter a control structure. This
can make it harder for new developers to understand the code quickly.
2
Selection Statement
A selection statement provides the means of choosing between two or
more paths of execution.
Selection statement fall into two general categories:
– Two-way selection
– Multiple-way selection
Statement-Level Control Structures
3
Two-way Selection Statements
The general form of a two-way selector is as follows:
if control_expression
then clause
else clause
Design issues
– What is the form and type of the control expression?
– How are the then and else clauses specified?
– How should the meaning of nested selectors be specified?
Statement-Level Control Structures
What is the form and type of the control expression?
•Form: The control expression is the condition you check to decide which block of code to executeFor example, x > 10 is a
control expression that checks if x is greater than 10.
•Type: The control expression must be of a boolean type, meaning it should evaluate to either true or false. In programming
languages, this is enforced so that you can only use expressions that can logically be true or false.
How are the then and else clauses specified?
•Then Clause: This is the block of code that runs if the control expression evaluates to true. You can write a single statement
or multiple statements. If you have multiple statements, they are usually grouped together.
•Else Clause: This is the block of code that runs if the control expression evaluates to false. Like the then clause, it can also be
a single statement or a block of statements.
•Specification: In many programming languages, you use curly braces {} to group multiple lines of code, or you use
indentation (like in Python) to show which lines belong to the then or else clauses.
How should the meaning of nested selectors be specified?
•Nested Selectors: This refers to having an if statement inside another if statement. It allows you to check additional
conditions based on the outcome of the first condition.
•Clarity: When you nest if statements, it’s important to keep the code clear and easy to read. You should use proper
indentation or braces to show which if belongs to which block of code.
•Evaluation Order: The outer if is evaluated first. If it’s true, the code inside it runs, which may include another if statement. If
the outer if is false, the else part runs, which can also contain another if.
4
The control expression
Control expressions are specified in parenthesis if the then reserved word
is not used to introduce the then clause, as in the C-based languages
In C89, which did not have a Boolean data type, arithmetic expressions
were used as control expressions
int a = 10, b = 20;
int x = 5;
if (a < b) { // This evaluates to true (1) because
if (x) { // This checks if x is non-zero (true)
10 is less than 20
printf("x is true\n");
printf("a is less than b\n");
} else {
} else {
printf("x is false\n");
printf("a is not less than b\n");
}
}
In contemporary languages, such as Java and C#, only Boolean expressions
can be used for control expressions
Statement-Level Control Structures
In C89, any non-zero integer value is considered true, while 0 is considered false. This means that you can use any
arithmetic expression that evaluates to an integer as a control expression in if, while, and other control statements.
5
Clause Form
In most contemporary languages, the then and else clauses either appear
as single statements or compound statements.
C-based languages use braces to form compound statements.
One exception is Perl, in which all then and else clauses must be
compound statements, even if they contain single statements
In Python and Ruby, clauses are statement sequences
Python uses indentation to define clauses
if x > y :
x=y
print " x was greater than y"
All statements equally indented are included in the compound statement.
Notice that rather than then, a colon is used to introduce the then clause
in the Python
Statement-Level Control Structures
6
Nesting Selectors
In Java and contemporary languages, the static semantics of the language
specify that the else clause is always paired with the nearest unpaired then
clause
If properly coded:
If not properly coded: if (sum == 0)
if (sum == 0) if (count == 0)
if (count == 0) result = 0;
result = 0; else
else result = 1;
result = 1;
A rule, rather than a syntactic entity, is used to provide the disambiguation
So, in the example, the else clause would be the alternative to the second
then clause
Statement-Level Control Structures
In Java and many other C-like programming languages, this is a well-known situation often referred to as the
"dangling else" problem.
The static semantics of the language resolve this ambiguity by pairing each else with the nearest preceding
unmatched if—even if that is not what the programmer intended visually.
7
Nesting Selectors
To force the alternative semantics in Java, a different
syntactic form is required, in which the inner if is put in
a compound, as in
if (sum == 0) {
if (count == 0)
result = 0;
}
else
result = 1;
Statement-Level Control Structures
In Java, to force the else to associate with the outer if rather than the nearest inner if, you must use explicit
block structure using curly braces {}.
This syntactic change is necessary to override the default static semantics that pair an else with the nearest
unmatched if.
8
Nesting Selectors
– C, C++, and C# have the same problem as Java with
selection statement nesting
– Ruby, statement sequences as clauses:
if sum == 0 then
if count == 0 then
result = 0
else
result = 1
end
end
Statement-Level Control Structures
C, C++, Java, C#: Dangling Else Problem
All of these C-style languages share the same ambiguity due to their grammar and semantics, where:
•An else always pairs with the closest unmatched if.
•To avoid confusion, braces {} are used to explicitly define blocks and control else pairing.
•Ruby avoids the dangling else issue by using end to close each block, which clearly defines scope for each if.
9
Nesting Selectors
Python, all statements uses indentation to define
clauses
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1
Statement-Level Control Structures
10
Multiple Selection Constructs
The multiple selection construct allows the selection of one
of any number of statements or statement groups.
Design Issues
– What is the form and type of the control expression?
– How are the selectable segments specified?
– Is execution flow through the structure restricted to
include just a single selectable segment?
– How are case values specified?
– What is done about unrepresented expression values?
Statement-Level Control Structures
What is the form and type of the control expression?
•This refers to what kinds of expressions can be evaluated to decide which branch to take
How are the selectable segments specified?
•This defines the structure of the branches. C/C++/Java: case value: followed by statements.
Is execution flow restricted to a single selectable segment?
•In some languages, control can fall through to subsequent branches if not explicitly stopped.
How are case values specified?
•The format and rules for assigning values to branches:
What is done about unrepresented expression values?
•What happens if no case matches?
11
Multiple Selection Constructs
C, C++, Java, and JavaScript switch
switch (expression) {
case constant_expression1 : statement1;
...
case constant_expressionn : statementn;
[default: statementn+1]
}
Statement-Level Control Structures
12
Multiple Selection Constructs
C# switch
– C# switch statement differs from C-based in that C# has static semantic rule disallows
the implicit execution of more than one segment
– The rule is that every selectable segment must end with an explicit unconditional branch
statement either a break, which transfers control out of the switch construct, or a goto,
which can transfer control to on of the selectable segments. C# switch statement example:
switch (value) {
case -1: Negatives++;
break;
case 0: Positives++;
goto case 1;
case 1: Positives ++;
default: Console.WriteLine(“Error in switch \n”);
}
Statement-Level Control Structures
No Fall-Through
•In C#, only one case is run, unless you tell it to go to another.
•Unlike C or C++, it won't accidentally run the next case unless you use goto.
Each Case Must End Clearly
•You must end each case with something like:
• break (stop the switch)
• goto case (jump to another case)
• return (exit the method)
• throw (throw an error)
Default Case
•If no case matches, C# will run the default: block — just like an "else" in an if.
13
Multiple Selection Constructs
Multiple Selection Using if
– Multiple Selectors can appear as direct extensions to two-way
selectors, using else-if clauses
– Ex, Python selector statement (note that else-if is spelled elif in
Python):
if count < 10 :
bag1 = True
elif count < 100 :
bag2 = True
elif count < 1000 :
bag3 = True
Statement-Level Control Structures
14
Multiple Selection Constructs
which is equivalent to the following:
if count < 10 :
bag1 = True
else :
if Count < 100 :
bag2 = True
else :
if Count < 1000 :
bag3 = True
The elsif version is the more readable of the two.
Statement-Level Control Structures
15
Multiple Selection Constructs
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
Notice that this example is not easily simulated with a switch-case
statement, because each selectable statement is chosen on the basis of a
Boolean expression
Statement-Level Control Structures
16
Iterative Statements
An iterative statement is one that cause a statement or collection of
statements to be executed zero, one, or more times
The repeated execution of a statement or compound statement is
accomplished either by iteration or recursion
An iterative statement is often called loop
Iteration is the very essence of the power of computer
The repeated execution of a statement is often accomplished in a
functional language by recursion rather than by iteration
Statement-Level Control Structures
Iteration
•Uses loops like while, for, or do-while.
•Common in imperative languages like C, Java, Python.
•Repeats a block of code until a condition is false.
Recursion
•A function calls itself to solve a problem.
•Often used in functional languages like Haskell, Scheme.
17
Iterative Statements
General design issues for iteration control statements:
– How is iteration controlled?
– Where should the control mechanism appear in the loop statement?
The primary possibilities for iteration control are logical, counting, or a
combination of the two
The main choices for the location of the control mechanism are the top of
the loop or the bottom of the loop
The body of a loop is the collection of statements whose execution is
controlled by the iteration statement
The term pretest means that the loop completion occurs before the loop
body is executed
The term posttest means that the loop completion occurs after the loop
body is executed
The iteration statement and the associated loop body together form an
iteration statement
Statement-Level Control Structures
18
Counter-Controlled Loops
A counting iterative control statement has a variable,
called the loop variable, in which the count value is
maintained
It also includes means of specifying the initial and
terminal values of the loop variable, and the difference
between sequential loop variable values, called the
stepsize.
The initial, terminal and stepsize are called the loop
parameters.
Statement-Level Control Structures
19
Counter-Controlled Loops
The for statement of the C-based languages
for ([expr_1] ; [expr_2] ; [expr_3])
loop body
– The loop body can be a single statement, a
compound statement, or a null statement
for (count = 1; count <= 10; count++)
Statement-Level Control Structures
20
Counter-Controlled Loops
– All of the expressions of C’s for are optional
– If the second expression is absent, it is an
infinite loop
– If the first and third expressions are absent, no
assumptions are made
Statement-Level Control Structures
21
Counter-Controlled Loops
– C’s for is more flexible than the counting loop statements of Fortran and Ada, because
each of the expressions can comprise multiple statements, which in turn allow multiple loop
variables that can be of any type
– Consider the following for statement:
for (count1 = 0, count2 = 1.0;
count1 <= 10 && count2 <= 100.0;
sum = ++count1 + count2, count2 *= 2.5)
;
Statement-Level Control Structures
22
Counter-Controlled Loops
– The for statement of C99 and C++ differs from earlier version of C in two ways:
• It can use an arithmetic expression or a Boolean expression for loop control
• The first expression can include variable definitions (scope is from the definition to
the end of the loop body), for example
for (int count = 0; count <= 10; count++) { . . . }
– The for statement of Java and C# is like that of C++, except that the loop control
expression is restricted to Boolean
Statement-Level Control Structures
The for statement in C99 and C++ includes improvements over earlier C versions that make it more flexible and
safer.
In Java and C#, the loop control (condition) must be Boolean.
You cannot use an integer expression like in older versions of C.
23
Counter-Controlled Loops
The for statement of Python
– The general form of Python’s for is:
for loop_variable in object:
- loop body names = ["Mike","Ana","Jun"] #<-LIST
[else: for name in names:
- else clause] print(name)
– The object is often range, which is either a list of values in brackets ([2,
4, 6]), or a call to the range function (range(5), which returns 0, 1, 2, 3, 4)
– The loop variable takes on the values specified in the given range, one
for each iteration
– The else clause, which is optional, is executed if the loop terminates
normally
Statement-Level Control Structures
24
Counter-Controlled Loops
– Consider the following example:
for count in [2, 4, 6] :
print count
produces
2
4
6
Statement-Level Control Structures
25
Thank you
to be continued…
26
Activity – group
• Design Your Own Loop Construct
– When designing a new loop, you should define:
• Initialization: How do you set up the loop to start? (2 points)
• Condition: What condition determines when the loop stops? (2 points)
• Iteration: How does the loop move forward? This could be updating variables or
changing states. (2 points)
– Define the Syntax: (4 point)
• Decide how your loop should look in terms of syntax.
Set Up Loop Initialization (5 points):
Define how the loop will start. For example: You may want to initialize variables or objects that
will be used inside the loop.
Define the Loop Condition (5 points):
Determine what will stop the loop. Is it based on a boolean condition? A counter reaching a
certain value?
Specify Iteration Behavior (5 points):
Define how the loop will "move" forward. Does it increment a variable, process data, or check a
different condition after each iteration?
Decide on Loop Termination (5 points):
Create rules for when the loop will stop. If you're designing a repeat-until loop, the condition is
checked after the body of the loop. For a while loop, it's checked before executing the body.
27