The if-else-if ladder

The if-else-if ladder

Published by: Nuru

Published date: 21 Jun 2021

The if-else-if ladder Photo

The if-else-if ladder

The if-else-if ladder is the type of nesting in which there is an if….else statement in every else part except the last else part. This type of nesting is frequently used in programs and is also known as else if ladder. This construct is if-else if ladder because of its appearance. The ‘if-else if’ ladder helps the user to decide from among the multiple options.

The general syntax for the ‘if-else if’ ladder is below:

If (condition1)

Statement-A;

Else if (condition2)

Statement-B;

Else if (condition3)

Statement-C;

………………

Else

Next statement;

There is an evaluation of the sentence from the top downward. As soon as a true condition is found, the statement associated with it is executed. And, the rest of the ladder is bypassed. If none of the conditions are true, there is the execution of the final ‘else’ statement. If the final else is not present, no actions take place if all other conditions are false.

Working of the 'if-else-if ladder' statement

  1. Control falls into the if block.
  2. The flow jumps to Condition 1.
  3. There is the testing of the condition.
    1. If Condition yields true, goto Step 4.
    2. And, If Condition yields false, go to Step 5.
  4. Then, there is the execution of the present block statement. Go to Step 7.
  5. Flow jumps to Condition 2.
    1. If Condition yields true, go to step 4.
    2. Now, If Condition yields false, go to Step 6.
  6. Then, the flow jumps to Condition 3.
    1. If Condition yields true, go to step 4.
    2. And, If Condition yields false, execute the else block. Go to Step 7.
  7. Exiting the if-else-if ladder.

if-else-if ladder

Fig: Flowchart showing the if-else if ladder statement

 

Now, let us see a program that shows the execution of the if-else if ladder statement. It is below.

if-else-if ladderif-else-if ladder

Fig: Showing the program and output for 'if-else if ladder statement'.