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:
Here:
-
The first
ifcheckscondition1. -
Inside it, another
ifcheckscondition2. -
This is a nested if.
Key Points:
-
Decision within a decision: The inner selection is only evaluated if the outer condition is true.
-
Multiple levels allowed: You can nest as many selection statements as needed, but readability may suffer.
-
Alternative structures: Nested
if-elsecan sometimes be replaced by logical operators (&&,||) orswitch-casestatements for clarity. -
Indentation matters: Proper indentation is crucial to avoid confusion in nested structures.
-
Outer
ifcheckAdvantages:
-
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.