4.3. Worked Example: Write Selection Statements¶
Subgoals for Writing Selection Statements
If Statement
Define how many mutually exclusive paths are needed
Order from most restrictive/selective group to least restrictive
Write if statement with Boolean expression
Follow with true bracket including action
Follow with else bracket
Repeat until all groups and actions are accounted for
OR Switch Statement
Determine variable / expression for mutually exclusive ranges
Write switch statement based on variable / expression
Each range is a ‘case’
Include break statements and default case if needed
You can watch this video or read through the content below it.
Problem: Write the Java selection statements to solve the following specifications:
If integer variable currentNumber is odd, change its value so that it is now 4 times currentNumber plus 1; otherwise change its value so that it is now half of currentNumber (rounded down when currentNumber is odd).
SG1: Define how many mutually exclusive paths are needed
In this case, the problem says to do one action if variable is odd, and a different action otherwise.
Integer variable can only be odd or even, so there are 2 mutually exclusive paths. An if statement is best approach
SG2: Order from most restrictive/selective group to least restrictive
Since there are only 2 branches, order should not matter
SG3: Write if statement with Boolean expression
To determine if currentNumber is odd, we can check the remainder after dividing by 2 (modulo): if (currentNumber % 2 == 1)
SG4: Follow with true bracket including action
In the true branch, change value to 4 times + 1
if (currentNumber % 2 == 1)
{
currentNumber = currentNumber * 4 + 1;
}
SG5 : Follow with else bracket
In the else branch, change value to half current value. Note that integer division automatically truncates i.e. rounds down.
if (currentNumber % 2 == 1)
{
currentNumber = currentNumber * 4 + 1;
}
else
{
currenNumber /= 2;
}
SG6: Repeat until all groups and actions are accounted for
Not used – only two branches
Equivalent solution using the other ordering of the range/case groups.
if (currentNumber % 2 == 0)
{
currentNumber /= 2;
}
else
{
currentNumber = currentNumber * 4 + 1;
}
Practice Pages