In the last segment, you learnt about one of the most fundamental programming concepts, i.e. if...else statements. if...else checks for a certain condition, and there are two possibilities. If the condition is true, then the code written inside the if-block is executed. In case the condition is false, the code written inside the else-block is executed.
But what if there is more than one condition that needs to be checked? Let’s see how that is handled.
So as you just saw, if more than one condition needs to be tackled, we can form an if..else..if chain. If any of the conditions hold true, the code written inside its block is executed. After the code inside a block is executed, the control comes out of the if-else-if block. If neither of the conditions holds true, the code written inside the else-block is executed.
Let’s learn more about if..else..if chain in detail by applying it to the example of checking whether a number is positive, negative or zero.
In the previous video, you learnt a practical implementation of the if...else...if chain, wherein you found out if a number is positive, negative or equal to zero. In this case, there are 2 conditions to be evaluated - Is the number equal to zero? Is the number greater than zero (i.e positive)?
As there are 2 conditions, a simple if..else statement won’t work, hence you need to use if..else..if chain.