Codio Unit 2: Selection and Iteration
2.1 Algorithms with Selection and Iteration
Selection algorithms
int temperature = 25;
if (temperature > 30) {
System.out.println("It's hot outside!");
} else {
System.out.println("The weather is pleasant.");
}for loop
for (int i = 1; i <= 5; i++) {
System.out.println("This is repetition " + i);
}while loop
boolean clothesRemain = true;
while (clothesRemain)
{
boolean isWhite = sortClothes();
if (isWhite)
{
usebleach();
} else
{
useRegularDetergent();
}
washClothes();
clothesRemain = checkForRemainingClothes();
}Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
Repetition is when a process repeats itself until a desired outcome is reached.
2.2 Boolean Expressions
2.3 if Statements
A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.

A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.

2.4 Nested if Statements
A multi-way selection (if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multi-way selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.

2.5 Compound Boolean Statements
The expression
!aevaluates to true ifais false and evaluates to false otherwise.The expression
a && bevaluates to true if bothaandbare true and evaluates to false otherwise.The expression
a || bevaluates to true ifais true,bis true, or both, and evaluates to false otherwise.The order of precedence for evaluating logical operators is
!(not),&&(and), then||(or).An expression involving logical operators evaluates to a Boolean value.
Short-circuit evaluation occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated.
2.6 Comparing Boolean expressions
2.7 While Loops
2.8 For loops
2.9 Implementing Selection and Iteration Algorithms
2.10 Implementing String Algorithms
String Class methods
Method | Description |
|---|---|
| Returns the number of characters in a |
| Returns the substring beginning at index |
| Returns |
| Returns the index of the first occurrence of |
| Returns |