Lecture on Basic Structures in Program Logic and Design

Jun 18, 2024

Program Logic and Design: Lecture on Basic Structures

Introduction

  • Goal: Discuss three basic programming structures.
  • Avoid "spaghetti code" (unstructured programs).
  • Focus on structured programming.

Three Basic Structures

Sequence Structure

  • Definition: Performs actions in a linear order.
  • Characteristics: No branching or skipping tasks.
  • Example: Driving directions - actions executed step-by-step (e.g., turn right, turn left).
  • Diagram Representation: Stacking boxes on top of each other.

Selection Structures

  • Definition: Also known as decision structures; they involve making decisions.
  • Symbol: Diamond shape in flowcharts.
  • Types:
    • Dual Alternative Ifs (If-Then-Else):
      • Contains two alternatives (yes or no)
      • Example: If traffic is backed up, follow an alternate path.
    • Single Alternative Ifs:
      • Contains only one alternative followed by an end (e.g., If itโ€™s raining, then take an umbrella).
      • Null case: If condition is false, nothing happens.
  • Flowchart: Begins with a decision symbol and branches join at the bottom.

Loop Structures

  • Definition: Repeats a set of actions while a condition remains true (called repetition or iteration).
  • Common Form: While loop, where condition is tested first.
  • Example: While hungry, continue eating.
  • Flowchart Representation: Loop body symbols return to the decision point until the condition is false.

Stacking Structures

  • Concept: Structures can be stacked end to end (sequence, selection, loop).
  • Mistakes to Avoid: Do not interweave structures.
  • End Statements:
    • End If: Ends an if-then-else structure.
    • End While: Ends a loop structure.
  • Variability: Structures can be stacked in infinite ways.
  • Import Rule: Yes/No for flowcharts, True/False for pseudocode.

Nesting Structures

  • Definition: Placing one structure within another and indenting accordingly.
  • Block: Group of statements executed as a single unit (e.g., curly braces {} in Java/C++).
  • Examples:
    • Selection structure nested within a sequence.
    • Loop within a selection.
  • Alignment: End statements (End If, End While) should be vertically aligned.

Characteristics of Structured Programs

  • Single Entry/Exit Points:
    • Each structure has a single entry and single exit point.
    • These points are where structures can be connected.
  • Combining Structures:
    • Structures can be connected or nested within each other only at entry/exit points.

Summary

  • Foundational Structures:
    • Sequences, Selections, and Loops form the basis of structured programs.
  • Connections: Entry and exit points are crucial for stacking/nesting structures.
  • Example: Page 94 & Figure 3.11 in the textbook for detailed examples and diagrams.

Next Topic

  • Priming input to structure a program.