topic badge
India
Class V

Branching

Lesson

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$10 and $20$20
  • If it is even, divide by $2$2.
  • If it is odd, add one and then divide by $2$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.

Practice Questions

Question 1

Follow the algorithm.

  1. Start with the number $8$8.

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

 

Question 2

Follow the algorithm.

  1. Start with the number $8$8.

    If it is even, add $7$7 then double it. If it is odd, double it then add $7$7.

 

Question 3

For each of the numbers below, follow this rounding algorithm:

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

If the digit after the decimal point is less than $5$5, write the number without the decimal part.

  1. Use the algorithm to round $7.2$7.2

  2. Use the algorithm to round $3.5$3.5

What is Mathspace

About Mathspace