Session 6 : Control Structures Statement
October27
Selection Statements
- A selection statement provides the means of choosing between two or more paths of execution
- Two general categories:
- Two-way selectors
- Multiple-way selectors
Two-Way Selection Statements
- General form:
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?
Iterative Statements
- The repeated execution of a statement or compound statement is accomplished either by iteration or recursion
- General design issues for iteration control statements:
- How is iteration controlled?
- Where is the control mechanism in 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)){
…
}
- PHP
- current points at one element of the array
- next moves current to the next element
- reset moves current to the first element
- Java 5.0 (uses for, although it is called foreach)
For arrays and any other class that implements the Iterable interface, e.g., ArrayList
for (String myElement : myList) { … }