Program Logic and Design: Basic Structures

May 23, 2024

Program Logic and Design: Basic Structures

Introduction

  • Importance of avoiding spaghetti code (unstructured programs).
  • Focus on structured programming using three basic structures.

Three Basic Structures

  1. Sequence Structure

    • Performs actions in order without branching or skipping.
    • Example: Driving directions.
    • Actions are performed step by step until the sequence ends.
    • Visual: Boxes stacked on top of each other.
  2. Selection Structures (Decision Structures)

    • Dual Alternative Ifs (If-Then-Else)
      • Two alternatives (Yes or No).
      • Example: Traffic decisions based on road conditions.
      • Always close an If statement.
    • Single Alternative Ifs
      • Only one alternative action if condition is true.
      • Example: Taking an umbrella if it is raining.
      • Null case: No action if condition is false.
    • Flowchart and Pseudocode
      • Starts with a decision symbol (diamond shape).
      • Branches (flow lines) join at the bottom.
  3. Loop Structure (Repetition or Iteration)

    • Repeats actions while a condition remains true.
    • While Loop
      • Tests condition first.
      • Continues looping until condition is false.
      • Example: Asking for people's names until 'zzz' is entered.
    • Importance of not having excessive repeating lines in the code.

Stacking and Nesting Structures

  • Stacking Structures

    • Attaching structures end to end (e.g., sequence -> selection -> loop).
    • Structures must be stacked without interweaving lines.
    • Each structure must fully complete before stacking another.
  • Nesting Structures

    • Placing one structure within another.
    • Example: A sequence within a selection.
    • Indentation is crucial for nested structures (e.g., use of curly braces in Java).
    • Align nested structures vertically (e.g., EndIf aligns with If).
    • No limits on the number of nesting levels.

Summary

  • Programs can include combinations of the three basic structures.
  • Each structure has a single entry and exit point.
  • Structures can be stacked or nested to create complex logic.

Next Topic

  • Priming input to structure a program (covered in the next video).