Structured programming notes

3. Nested Control Structures

3.1. Nested Selection Statements

A nested selection statement is a decision-making structure where one selection statement is placed inside another. In simpler terms, it’s like asking a question inside another question. This is commonly used in programming when you need to make more complex decisions.

Structure:

The most common selection statements are if, if-else, and switch. In nested selection, these statements are placed inside the body of another selection statement.

Example in pseudocode:

 
if (condition1) { // Code block for condition1 true if (condition2) { // Code block for condition2 true } else { // Code block for condition2 false } } else { // Code block for condition1 false }

Here:

  • The first if checks condition1.

  • Inside it, another if checks condition2.

  • This is a nested if.

Key Points:

  1. Decision within a decision: The inner selection is only evaluated if the outer condition is true.

  2. Multiple levels allowed: You can nest as many selection statements as needed, but readability may suffer.

  3. Alternative structures: Nested if-else can sometimes be replaced by logical operators (&&, ||) or switch-case statements for clarity.

  4. Indentation matters: Proper indentation is crucial to avoid confusion in nested structures.

    

  • Outer if checkAdvantages:

  • Allows handling complex decision-making.

  • Can check multiple conditions step by step.

Disadvantages:

  • Too many levels of nesting make code hard to read and maintain.

  • Can be simplified using logical operators or functions.