B2.3.1 Construct programs that implement the correct sequence of code instructions to meet program objectives.

B2.3.1 Construct programs that implement the correct sequence of code instructions to meet program objectives. 
• The impact of instruction order on program functionality 
• Ways to avoid errors, such as infinite loops, deadlock, incorrect output

The Big Idea

A program is ultimately a sequence of instructions that the computer executes one by one. The order of these instructions is critical: changing it can alter the logic, behavior, or outcome of a program entirely. Understanding how to organize instructions correctly and intentionally is essential to writing software that works as expected.

When constructing a program, the developer’s goal is to ensure that each step logically follows the previous one, preserving the intended control flow, satisfying the input-output transformation, and maintaining the correct state of the system throughout execution.


1. The Impact of Instruction Order on Program Functionality

The sequence of code instructions determines program behavior. A program may be syntactically valid but functionally incorrect if instructions are placed in the wrong order.

Example 1: Incorrect Order Produces Incorrect Output (Python)

print("Welcome")
name = input("What is your name? ")

Output:

Welcome
What is your name? John

Now consider:

name = input("What is your name? ")
print("Welcome")

Here the user sees no greeting until after input is provided, which may confuse them.


Example 2: Initializing Before Using a Variable (Java)

int x;
System.out.println(x);  // Compilation error: variable x might not have been initialized
x = 10;

Correct order:

int x = 10;
System.out.println(x);

Example 3: Control Flow and Logic

total = 0
for i in range(5):
    total += i
print("Done")
print(total)

If print("Done") were placed inside the loop, it would execute 5 times, not once.


2. Consequences of Incorrect Sequencing

Mistake TypeDescriptionEffect on Program
Premature executionAn operation is done before a required condition is metCrashes or incorrect results
Late executionCritical setup is done after dependent code has runNull/undefined behavior
Skipped executionMissing conditional blocks due to logic errorsLogical failures, silent bugs
Repeated executionPlacing operations inside a loop unintentionallyPerformance issues, duplicated output

3. Avoiding Errors from Misordered Instructions

3.1 Infinite Loops

An infinite loop occurs when the termination condition of a loop is never met.

Example:

i = 0
while i < 5:
    print(i)
    # i is never incremented — loop runs forever

Fix:

i = 0
while i < 5:
    print(i)
    i += 1

3.2 Deadlock (Advanced Concept)

In concurrent programming (e.g. multithreading), deadlock occurs when two or more processes wait indefinitely for each other to release resources.

Example (Conceptual):

  • Thread A locks resource X and waits for Y.
  • Thread B locks resource Y and waits for X.
  • Neither can proceed → deadlock.

Prevention Strategies:

  • Always acquire resources in a consistent order.
  • Use timeouts when waiting for resources.

3.3 Incorrect Output

Caused by logic being implemented in the wrong order or dependent variables being used before they're updated.

Example:

radius = 5
area = 3.14 * radius * radius
radius = float(input("Enter radius: "))  # Too late — area already calculated
print("Area:", area)

Fix:

radius = float(input("Enter radius: "))
area = 3.14 * radius * radius
print("Area:", area)

4. Techniques for Constructing Well-Ordered Programs

4.1 Stepwise Refinement

  • Break a problem into smaller tasks.
  • Order the tasks logically based on dependencies.
  • Implement each step in the correct sequence.

4.2 Use of Pseudocode or Flowcharts

Helps visualize control flow before coding.

Example Flow:

Start → Input → Process → Decision → Output → End

4.3 Testing with Trace Tables

Manually simulate code execution to verify:

  • The correct sequence of variable assignments.
  • Loop iterations and updates.
  • Output at each step.

5. Worked Example (Python)

Task:

Prompt the user for two numbers, add them, and print the result.

Incorrect:

sum = a + b
a = int(input("Enter A: "))
b = int(input("Enter B: "))
print(sum)

Correct:

a = int(input("Enter A: "))
b = int(input("Enter B: "))
sum = a + b
print(sum)

Summary

ConceptExplanation
Instruction sequencingThe logical order in which code is written and executed
Incorrect order consequencesCrashes, logic errors, infinite loops, deadlocks, wrong output
Best practicesUse pseudocode, stepwise refinement, trace tables, testing
Common errorsUsing uninitialized variables, missing loop updates, misplaced conditionals

Summary

Correct instruction sequencing is fundamental to program correctness. It's not just about getting the syntax right—it’s about ensuring that every action in the program occurs in the correct logical order. Mastering control flow and understanding data dependencies is what elevates a programmer from simply "writing code" to designing solutions.


In-class problem set: 

  • If the order of instructions is wrong, the program will not behave correctly.
  • Students can trace the code line by line to see why order matters.
  • We can also show where infinite loops or incorrect outputs might occur if sequencing is mishandled.

Here’s a small worked example program you can use:

# Homework Reminder Program
# Standard: B2.3.1 - Construct programs with correct sequence of instructions

# Step 1: Create an empty list to store homework
homework_list = []

# Step 2: Ask the user how many assignments they have
num_assignments = int(input("How many homework assignments do you have? "))

# Step 3: Use a loop to collect each assignment
for i in range(num_assignments):
    assignment = input(f"Enter homework #{i+1}: ")
    homework_list.append(assignment)

# Step 4: Print a reminder message BEFORE listing homework
print("\nHere are your homework assignments for today:")

# Step 5: Display the homework list in order
for hw in homework_list:
    print("-", hw)

# Step 6: End program with a motivational message
print("\nGood luck! Remember to finish your homework on time!")

Why this works for B2.3.1 (Sequence of Instructions)

  1. Correct sequence:
    • The list must be created before adding homework.
    • Asking for input must come before appending.
    • The reminder message must be printed before showing the list.
  2. Impact of wrong order:
    • If we print the homework list before adding assignments, it will be empty.
    • If we try to use the loop before asking how many assignments there are, the program won’t know how many times to repeat.
  3. Avoiding errors:
    • Using int(input()) ensures we get a number for the loop.
    • The loop ensures we don’t repeat infinitely (it ends after num_assignments times).

Possible class activity

  • Task: Ask students to change the order of instructions (e.g., move Step 4 above Step 2) and predict what will happen.
  • Discussion point: “Why does the order of instructions matter in achieving the program’s objective?”