Structured programming notes

3. Nested Control Structures

Nested Control Structures occur when one control structure is placed inside another. This allows programs to handle more complex logic by combining multiple decisions or loops. Nested structures are widely used in structured programming to perform tasks that require multi-level decision-making or repeated actions within repeated actions.

Types of Nested Control Structures

  1. Nested Selection Statements

    • An if or switch statement placed inside another selection statement.

    • Useful for situations where a decision depends on the result of a previous decision.

    Example (Nested if):

     
    int marks = 85; if (marks >= 50) { if (marks >= 75) { printf("Distinction"); } else { printf("Pass"); } } else { printf("Fail"); }
  2. Nested Loops

    • A loop inside another loop.

    • Commonly used for multi-dimensional data, like matrices or tables.

    Example (Nested for loop): Print a 3x3 multiplication table.

     
    for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { printf("%d ", i * j); } printf("\n"); }
  3. Combination of Selection and Iteration

    • Loops containing decision statements or decisions containing loops.

    • Allows for flexible, real-world logic in programs.

    Example: Print even numbers from 1 to 10.

     
    for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { printf("%d ", i); } }

Key Points

  • Nested structures increase program flexibility and problem-solving capability.

  • Over-nesting can reduce readability, so maintain clarity.

  • Always ensure proper indentation and block structure to avoid logical errors.

Summary

Nested Control Structures allow combining loops and decision-making constructs to handle complex programming logic. They are essential for tasks like multi-level decision-making, table manipulation, and processing multi-dimensional data.