
Nested if else (programming)

Upgrade for more content
True or false? When there is more than one condition to be tested, you can use nested statements.
Lina has taught her robot to give out chocolate to Maria or Leon. The robot picks up a piece of chocolate. It is milk and the condition “milk chocolate” is true. The robot gives the chocolate to Maria. But Maria doesn’t want it even though it is milk chocolate.
I’m allergic to nuts. So if there are nuts in the chocolate I can’t eat it. So Lina needs to give new instructions to the robot, that if it is milk chocolate and if there are nuts in it, the robot should not give the chocolate to Maria. What shall we do with the chocolate? Leon only likes dark chocolate.
Just put it back in the box. When the robot picks up a piece of chocolate, it looks to see if it is milk chocolate. But that’s no longer enough, because Maria is allergic to nuts. If it is milk chocolate, the robot should look to see also if there are nuts in it. There will be an if-instruction within an if-instruction that when the condition ‘there are nuts in it’ is also true, the robot puts the chocolate back in the box.
Else the robot gives the piece of chocolate to Maria. But when the condition ‘milk chocolate’ is not true, it must of course be dark, which Leon likes. So the instruction to the robot should be, ‘Give Leon chocolate.’ Let’s test the new pseudocode. The robot picks up a piece of chocolate and it is milk chocolate. The first condition is “milk chocolate” and that is true.
The next condition that is tested is “nuts”. Is the condition true or false? The robot examines very carefully and sees that there are nuts in this piece of chocolate. That condition is true. So the robot follows the instruction to put the piece of chocolate back in the box.
The rest of instructions are performed only if the condition ‘milk chocolate’ is false, or if ‘milk chocolate‘ is true, and ‘nuts’ is false. The program ends when the robot puts the piece of chocolate back. Let’s start the program again, to try with a new piece. Again this time, it is “milk chocolate”. So the first condition is true.
The next thing the robot investigates is if ‘there are nuts in it.’ There are no nuts, and the second condition is false. That leads to the instruction: else ‘Give Maria chocolate’. And then the program ends. Lina has written an if-instruction within another if-instruction. This is called a nested if-statement.
With nested if-statements the robot can decide whether it is milk or dark chocolate and whether the milk chocolate contains nuts. Now Maria can relish her piece of chocolate without worrying that there might be nuts in it.