Purpose
- Control constructs allow us to control the flow of execution other than by calling and returning from methods. They fall into to two categories: conditional control constructs and and looping control constructs.
Conditional control constructs
- Conditional statements interrupt the normal sequential flow of control from one statement to the next by allowing some code to execute or not depending on the values of a
boolean
condition.
- A simple
if
statement affect the flow of control by executing the statements in the if
’s body only if the if
’s boolean
condition evaluates to true
. This provides a one-way selection where a set of statements either is or is not executed, depending on the condition.
- A two-way selection, written with an
if
/else
, causes either one set of statements or another to be executed, one when the boolean condition is true and the other when it is false.
- A multi-way selection, written with an
if
, one ore more else if
s, and optionally a final else
, chooses one of several sets of statements to execute based on a number of different boolean
conditions. The code that executes is the body of the first if
whose condition is true
or the body of the else
if all the conditions are false
.
- Any code can go in the body of an
if
or else
including other if
, if
/else
, and if
/else if
/else
statements, producing nested conditional statements.
- Technically
if
/else if
/else
statements are just regular if
/else
statements with a nested if
/else
statement but we write them chained together when we want to express a multi-way selection.
Looping control constructs
- Looping control constructs, also called iteration constructs, change the normal flow of control by repeating a sequence of statements zero or more times.
- In both
while
and for
loops, a boolean
expression is evaluated before each iteration of the loop’s body, including the first. When the expression evaluates to true
, the loop body is executed. Then the loop repeats this process until the boolean
expression evaluates to false..
- If the
boolean
expression evaluates to false the first time it is evaluated, the loop body is not executed at all. Conversely, if the boolean
expression always evaluates to true
, the loop is an infinite loop.
- A
while
loop consists of just two parts: the condition and the body.
- A
while
loop executes by evaluating the condition. If the condition is true
it then executes the body and repeats, back at the condition. Otherwise the loop ends.
- Both the condition and the body will usually refer to variables defined before the loop. If the condition depends on the values of one or more variables and the body contains code that changes those variables, the condition can eventually become
false
and the loop will stop.
while
loops are most useful when you do not know, before the loop starts, exactly how many times it needs to run.
- A
for
loop consists of a header and a body.
- The header of a
for
loop consists of three parts, enclosed in parentheses and separated by semicolons: the initialization clause, the condition, and the update clause.
- The initialization clause is run once, before anything else in the loop. Typically the initialization clause declares and initializes a variable called the loop variable.
- The condition is evaluated before each iteration of the loop and the loop only continues if it evaluates to
true
. Usually the condition is some expression involving the loop variable.
- The update clause runs after the body of the loop and just before the next evaluation of the condition. The update clause usually updates the loop variable, typically by incrementing or decrementing it.
- The body of the
for
loop is executed after the condition is evaluated and before the update clause. Code within the body can refer to the loop variable declared in the loop header.
for
loops are typically used when we know, before the loop starts, how many times we want to iterate, e.g. once for every character in a string or element of an array.
- A
for
loop can be rewritten into an equivalent while
loop and vice versa, though the while
loop will need some code before the loop proper to perform the role of the for
loop’s initialization clause and the update clause will need to appear within the body of the while
loop.
- The enhanced
for
loop provides a concise way to traverse an array or an ArrayList
in the common case when we only need to deal with one element at a time and don’t care about the index.
- The enhanced
for
loop consists of a simplified header consisting of just a variable declaration, a colon, and an expression that evaluates to an array or an ArrayList
, and a body.
- The body of an enhanced
for
loop is executed once for each element of the array or ArrayList
with the variable assigned the value of each element in turn.
- The loop variable in an enhanced
for
loop is just a regular variable. Assigning a new value to it has no effect on the array itself.
- The body of a loop can contain any statements including other loops.
- Nested loops are just loops that appear in the body of another loop.
- When a loop is nested inside another loop, the inner loop must complete before the outer loop can continue.
- Since executing a
return
statement always immediately returns from the current method, it can be used to break out of a loop.\note{There are other constructs, not covered in the AP curriculum for controlling loop behavior. A break
statement causes the current loop to exit immediately while a continue
statement causes the current loop to jump immediately to its next iteration.}
- “Off by one” errors occur when the iteration statement loops one time too many or one time too few, for instance for (int i = 0; i <= s.length(); i++) rather than for (int i = 0; i < s.length(); i++) when iterating over the characters of a string.
- Unintended infinite loops occur when the condition never becomes false, often due to a bug in the update code.
- See [counting loops] for another summary of different kinds of loops.
- Looping over the individual elements of an array is also called traversing the array.
- Traversing an array with a standard
for
or while
loop requires using an index to access each element of the array.
- 2d arrays are typically traversed using nested loops.
- Since 2d arrays are stored as arrays of arrays, the outer loop iterates over the array whose elements are 1d arrays and the inner loop iterates over the elements of the 1d array.
- In the outer loop of nested enhanced
for
loops used to traverse a 2d array, the type of the loop variable must be the type of each row, i.e. a 1d array. In the inner loop, the type of the loop variable is the actual element type.