Skip to main content

Section 6.1 Worked Example: Write Selection Statements

Subgoals for Writing Selection Statements.

If Statement
  1. Define how many mutually exclusive paths are needed
  2. Order from most restrictive/selective group to least restrictive
  3. Write if statement with Boolean expression
  4. Follow with true bracket including action
  5. Follow with else bracket
  6. Repeat until all groups and actions are accounted for
OR Switch Statement
  1. Determine variable / expression for mutually exclusive ranges
  2. Write switch statement based on variable / expression
  3. Each range is a ‘case’
  4. Include break statements and default case if needed

Subsection 6.1.1

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).

Subsection 6.1.2 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.
The value in an integer variable can only be odd or even, so there are 2 mutually exclusive paths. An if statement is the best approach.

Subsection 6.1.3 SG2: Order from most restrictive/selective group to least restrictive

In this example the order does not matter.

Subsection 6.1.4 SG3: Write if statement with Boolean expression

To determine if the value in currentNumber is odd, we can check the remainder after dividing by 2 (using the modulus operator): if (currentNumber % 2 == 1)

Subsection 6.1.5 SG4: Follow with true bracket including action

In the true branch, change value of currentNumber to be 4 times its current value and add 1.
if (currentNumber % 2 == 1)
{
       currentNumber = currentNumber * 4 + 1;
}

Subsection 6.1.6 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;
}

Subsection 6.1.7 SG6: Repeat until all groups and actions are accounted for

Not used – only two branches

Subsection 6.1.8 Equivalent solution using the other ordering of the range/case groups.

if (currentNumber % 2 == 0)
{
   currentNumber /= 2;
}
else
{
   currentNumber = currentNumber * 4 + 1;
}

Practice Pages.

You have attempted of activities on this page.