Skip to content
Binogi logo

Subjects

If else (programming)

If else (programming)

Video thumbnail
Play

True or false? When using "If else" instructions, in the movie's example, only one condition is required.

If else (programming)

Lina has bought a chocolate box with milk and dark chocolates. She has taught her robot to give Maria and Leon their favourite variety. This is what Lina’s pseudocode instructions to the robot look like: Pick up a chocolate. If it is milk chocolate give the chocolate to Maria. If it is dark chocolate give the chocolate to Leon.

Let’s see how the pseudocode works. The robot picks up a piece of chocolate, and it happens to be milk. The first condition is “milk chocolate” - which is true, so… The robot gives the chocolate to Maria. Now the robot no longer has any chocolate in its hand. Nevertheless, it continues to the next instruction, which is: “If dark chocolate” But the robot isn’t holding a piece of chocolate.

So it is unnecessary to examine whether it's dark. How can Lina instruct the robot about that? Lina’s pseucocode has two conditions. If milk chocolate and If dark chocolate The chocolate box only contains two different kinds of chocolate. If it’s not milk chocolate that the robot picks up it must be dark chocolate.

The pseudocode can be changed to: If milk chocolate Give Maria chocolate Else Give Leon chocolate So, only one condition is required for Maria and Leon to get their favourite chocolate. Let’s test Lina’s pseudocode. The robot picks up a piece of chocolate, and it is milk. The condition “milk chocolate” is true. The robot gives Maria the chocolate.

And then… Did you see what happened? When the condition “milk chocolate” was true, the robot jumped over both the instruction “Else” and the instruction “Give Leon chocolate”. The program ends after the robot has given Maria the chocolate. Now let’s restart the program. The robot takes a new piece of chocolate.

This time it is dark. The condition is false and the program jumps over the instruction “Give Maria chocolate”. Now the robot knows that it’s not milk chocolate, and then the instructions “Else” and “Give Leon chocolate” are performed. It's enough for the robot to check if it's milk chocolate to know who is going to get the piece of chocolate. When Lina uses less conditions, the code becomes more efficient.

One test of whether a condition is true is enough, instead of two. Lina’s code becomes more easy to read. It’s more elegant code. Yes, actually, programmers do talk about "elegant code". The new pseudocode is a better way to solve the task.

It is a better algorithm for handing out chocolate. So now the code is more elegant than it was to start with. No clumsy-looking code here!