Uncategorized

Nested if – else

Nested if – else

Nesting means using one if else structure into another. Nested decision control structures are used when we need to code complex filters. Nested if structures are used when you need to filter your data through multiple interconnected conditions and different results need to be displayed depending upon the data.

Syntax:

Flow Chart:

How it works?

  • When a program encounter the if keyword, it checks for the condition specified in the brackets after if
    • If the condition evaluates as “true”, then the set of instructions under the if clause are executed
    • But if the condition evaluates as “false”, then the program enters another if structure
      • Now the program checks for the condition specified in this nested if structure;
        • If the condition evaluates as “true”, then the block of statements under if clause is executed
        • Otherwise, the statements under else clause are executed.
      • The program comes out of the nested if
    • The program comes out of the outer if clause.

Example:

Let’s look at this program which determines if the age in number entered by the user is in the 15 -20. The program also determines if the age entered by the user is valid or not.

Output:

Case 1:

Case 2:

Case 3:

Case 4:

Case 5:

Note:

It is also possible to nested the inner if in the if clause of the outer if, similarly as we have nested the if clause under the else of outer if.