topic badge
Australia
Year 6

9.06 Branching

Lesson

Branching

Branching is a term which in this context means things can go in different directions. Just like on a tree where branches are connected but going in different directions, we can have algorithms with branches.

Branching is used when you need to decide what to do next based on certain rules (conditions) and the data you're given. When you need to make a decision in coding, this is called a conditional. A conditional shows that there is branching and it explains what happens based on certain conditions.

The key word to look for with a branch is if.

Look at this algorithm. How many branches are there?

  • Choose a number between 10 and 20.

  • If it is even, divide by 2.

  • If it is odd, add one and then divide by 2.

That short algorithm has just two branches. The conditional is if something is even or if something is odd.

We display can display a branching algorithm in a  flow chart  (which you'll learn more about later). Here is the algorithm above displayed in a flow chart.

This image shows a flow chart with branches. Ask your teacher for more information.

Examples

Example 1

Follow the algorithm below:

  • Start with the number 8.

  • If the number is even, halve it.

  • If the number is odd, subtract one and halve it.

Worked Solution
Create a strategy

Recall that even numbers are multiples of 2.

Apply the idea

Since 8 is a multiple of 2, it is an even number. So, we need to follow the condition to halve it.

\displaystyle \text{Result}\displaystyle =\displaystyle 8\div2Halve the given number
\displaystyle =\displaystyle 4Evaluate

Example 2

Follow this rounding algorithm for the number 9.7:

  • If the digit after the decimal point is 5 or more than 5, round up to the next whole number.

  • If the digit after the decimal point is less than 5, write the number without the decimal value.

Worked Solution
Create a strategy

Look at the number after the decimal point to decide which condition to follow.

Apply the idea

The number after the decimal point in 9.7 is 7, which is more than 5.

So, we need to follow the first condition and round up to the next whole number which is 10.

Idea summary

When you need to make a decision in coding, this is called a conditional. A conditional shows that there is branching and it explains what happens based on certain conditions.

The key word to look for with a branch is if.

Outcomes

AC9M6A03

create and use algorithms involving a sequence of steps and decisions that use rules to generate sets of numbers; identify, interpret and explain emerging patterns

What is Mathspace

About Mathspace