Pseudocode and Loops – Comprehensive Study Notes

Pseudocode and Logic Errors – Comprehensive Study Notes

What is Pseudocode?
Pseudocode is a human-readable description of an algorithm that uses simple syntax and does not bind you to a specific programming language. It includes variables with assignment (either = or ←), INPUT and OUTPUT statements, and control structures such as conditionals (IF, ELSEIF, ELSE) and loops. Its purpose is to describe the logic of an algorithm in a way that mirrors code flow without worrying about language syntax.

Sample Analysis: How pseudocode differs from Python
The provided pseudocode program appears as:

INPUT numberOfPeople
costPerPerson = INPUT("Enter the cost per person")
IF numberOfPeople > 10 THEN
costPerPerson = costPerPerson * 0.9
ENDIF
totalCost ← numberOfPeople * costPerPerson
OUTPUT "The total cost is ", totalCost

Compared to Python, several differences stand out:

  • Variable assignment and input handling differ: Python would typically read input with input(), convert to a number (e.g., int or float), and assign it to a variable.
  • The pseudocode uses an end marker (ENDIF) to close the conditional, whereas Python relies on indentation.
  • The operator for assignment in some pseudocode is shown as = or ←, while Python uses = for assignment and relies on explicit multiplication with *.
  • The pseudocode places the cost adjustment logic inside a conditional with a clear end, while Python would implement the same logic using if numberOfPeople > 10: costPerPerson = costPerPerson * 0.9 and then proceed to compute the totalCost.
  • The OUTPUT statement concatenates strings and numeric values differently in pseudocode; Python would use print("The total cost is", totalCost) or formatted strings.

Validation – Range Check (1–10, then 1–20)
The range check example uses INPUT number and a conditional:

IF number >= 1 AND number <= 10 THEN
OUTPUT "That is correct"
ELSE
OUTPUT "That is incorrect"
ENDIF

This demonstrates a simple validation: the input is considered valid if it lies within the inclusive range [1, 10]. The prompt then asks you to try with different inputs and to modify the algorithm so that the valid range becomes [1, 20]. The key idea is adjusting the end of the range from 10 to 20, while preserving the lower bound at 1. A natural extension is to consider how to validate other ranges or multiple ranges by combining conditions (for example, using OR to allow numbers in either range).

Correcting Pseudocode and Logic Errors
Logic error: A logic error occurs when an algorithm’s structure causes it to produce an incorrect or unintended result even though the syntax is correct. Recognizing a logic error involves verifying that the algorithm’s flow and decisions align with the intended outcome, not just checking for syntax mistakes.

Change this pseudocode to add three numbers instead of two
The original snippet adds two numbers and outputs the total. The corrected version adds three numbers:

INPUT first
INPUT second
INPUT third
total = first + second + third
OUTPUT total

Correct Pseudocode (Three Inputs)
The example of corrected pseudocode with three inputs is shown as:

INPUT first
INPUT second
INPUT third
total = first + second + third
OUTPUT total

Change this algorithm to allow numbers between 100 and 200 (inclusive)
Original (as given) checks if number > 100 AND number < 200, which excludes 100 and 200 themselves. The corrected inclusive version is:

INPUT number
IF number >= 100 AND number <= 200 THEN
  OUTPUT "Correct"
ELSE
  OUTPUT "Incorrect"
ENDIF

Correct code (inclusive 100–200)

INPUT number
IF number >= 100 AND number <= 200 THEN
  OUTPUT "Correct"
ELSE
  OUTPUT "Incorrect"
ENDIF

Finding and correcting a smallest-number problem
The faulty algorithm attempts to determine the smallest of four inputs but contains several errors, including reusing the wrong variable in comparisons (e.g., using number1 in multiple places) and initializing smallest to an extreme value incorrectly, which can lead to logic issues. The corrected version is:

INPUT number1
INPUT number2
INPUT number3
INPUT number4
smallest = number1
IF number2 < smallest THEN smallest = number2 ENDIF
IF number3 < smallest THEN smallest = number3 ENDIF
IF number4 < smallest THEN smallest = number4 ENDIF
OUTPUT "The smallest number input was ", smallest

This version initializes smallest with number1 and then compares the remaining numbers, updating smallest when a smaller value is found.

Horse riding lesson cost algorithm – errors and corrections
The problem describes computing the cost of a horse riding lesson based on the lesson length (30 or 60 minutes) and rider level (1, 2, or 3), with potential private lessons doubling the cost. The description notes that a half-hour group lesson costs: Level 1 = $10, Level 2 = $15, Level 3 = $20. An hour lesson is twice the cost of a half-hour lesson, and a private lesson is twice the cost of a group lesson. The flawed pseudocode variants attempt to model this logic but include several pitfalls, such as mapping length to a factor incorrectly and mixing up private/group handling.

Correct approach (summary):

  • Define the base rates for levels: level1 = 10.0, level2 = 15.0, level3 = 20.0. These correspond to the cost for a 30-minute group lesson.
  • Map the chosen length to a factor to multiply by the base rate: 30 minutes → factor 1, 60 minutes → factor 2. This implements the rule that an hour lesson costs twice the half-hour lesson.
  • Read riderLevel in {1, 2, 3}; compute the initial cost as cost = lengthFactor * levelX, where levelX corresponds to the rider’s level.
  • Offer Private or Group option: if the user selects Private, double the cost again (cost = cost * 2).
  • Output the final total cost.

Two corrected pseudocode variants are shown. The first (Page 14) attempts to implement the logic but contains potential issues such as assuming an invalid level, mixing length handling, and combining decisions in a single conditional chain. The second (Page 15) provides a cleaner, corrected structure with explicit handling of 30 or 60 minutes mapped to length factors, a clear if-elseif chain for riderLevel, and a final private/group adjustment. The corrected structure results in a cost computed as:

Let ext{levelRate} o iglrace 1: 10, ext{2}: 15, ext{3}: 20 igrrace
Let ext{lengthFactor} o egin{cases} 1 & ext{if length = 30} \ 2 & ext{if length = 60} \ ext{(invalid input handled separately)} \ ext{default}
ext{(e.g., 1)} \
ext{end} \
ext{end} \
ext{end}

ight.
Then, for riderLevel ∈ {1, 2, 3}, costbeforeprivate = lengthFactor imes levelRate[riderLevel], and if type = "Private" (case-insensitive), cost = 2 imes costbeforeprivate; otherwise cost = costbeforeprivate. The final output is the total cost in dollars.

If you map 30 minutes to lengthFactor = 1 and 60 minutes to lengthFactor = 2, the 30-minute Level 1 group lesson costs $10, and the 60-minute Level 1 group lesson costs $20, consistent with the rule that an hour is twice a half-hour. A private lesson costs double the group lesson in either duration. The explicit, corrected pseudocode ensures all branches are well-defined and consistent with these numerical relationships.

Questions and quick checks (Pages 16–18)

  • Before changing an algorithm, you should answer what the algorithm is supposed to do and what it currently does. This helps you identify the discrepancy between intended behavior and actual behavior.
  • To find an error in a pseudocode algorithm, perform a dry run by tracing each line with various input data to observe the resulting state and outputs.
  • A logic error is an error where the code does not perform as intended or produce the expected output, even though the syntax may be correct.

Unlocking Repetition: The Power of Loops in Programming

Loops are core to programming because they enable repetition without duplicating code. They allow a computer to perform the same block of code multiple times, a process called iteration. Each execution of the loop body is one iteration. The loop continues until a specified condition signals to stop. If the loop’s stopping condition is never met, an infinite loop occurs, which can crash a program. The loop’s control condition acts like a question asked before each iteration: Is it time to stop yet? If the answer is no, the loop continues; if yes, it exits.

Two main types of loops
There are two primary categories: count-controlled loops and condition-controlled loops. Count-controlled loops repeat a fixed number of times, known in advance, while condition-controlled loops repeat until a specific condition is satisfied, but the exact number of iterations is not known beforehand. Count-controlled loops are often implemented as FOR loops, while condition-controlled loops are typically implemented via WHILE or REPEAT-UNTIL constructs, depending on the language.

Deep dive into count-controlled loops
Count-controlled loops are designed for fixed repetitions. They typically include a counter variable (the Counter), a starting value, and an end value. The counter is automatically incremented each time the loop runs. Common examples include counting from 1 to N, printing a message a fixed number of times, processing every item in a known-sized list, or repeating a drawing action (such as drawing four sides of a square).

Parts of a count-controlled loop
A count-controlled loop has three essential components: (1) The Variable (the counter), (2) Starting Value (the initial value of the counter), and (3) End Value (the value at which the loop stops after completing an iteration when the counter reaches this value). For counting from 1 to 10, a typical setup is: variable i, start 1, end 10. In pseudocode, the FOR loop combines these three parts into a single statement, promoting readability and reducing the chance of errors.

The FOR loop
The FOR loop is the canonical count-controlled loop. It encapsulates the counter variable, its starting value, and its end value in one structured form. The typical structure is FOR counter = start TO end, followed by END FOR. Inside the loop, only code between FOR and END FOR is executed repeatedly. The loop body runs with counter values from start up to end, inclusive, unless otherwise stated by language-specific syntax. Indentation is used to visually indicate the loop’s scope.

FOR loop examples
Example 1: Counting to 5
FOR counter = 1 TO 5
OUTPUT "The current count is: " + counter
END FOR
This prints the sequence from 1 to 5, inclusive.

Example 2: Repeating a Task
FOR i = 1 TO 3
OUTPUT "Hello, future programmer!"
END FOR
Here, the variable i counts from 1 to 3, but its value is not used in the output. The loop runs three times.

Key takeaways
Loops make programs efficient by avoiding repeated code blocks. Iteration is a single run through a loop. Loops stop when a condition is met; otherwise, they can run indefinitely. Count-controlled loops (FOR loops) run a fixed number of times, while condition-controlled loops run until a condition is satisfied.

Count-controlled loop anatomy and examples
A typical count-controlled loop has three parts: (1) The Variable (the loop counter), (2) Starting Value, and (3) End Value. For counting from 1 to 10, one might set the counter i, start = 1, end = 10. The FOR loop combines these into a single line, and the body is the code between FOR and END FOR. The loop’s iteration increments the counter by a fixed amount (often 1) on each pass. Common examples include counting from 1 to 10, repeating a message five times, processing items in a known-sized list, or repeating a geometric action such as drawing the sides of a polygon.

More FOR loop examples and exercises
A FOR loop example for counting up:

FOR counter = 1 TO 5
  OUTPUT "The current count is: " + counter
END FOR

This demonstrates how the counter variable advances through a known sequence and how output depends on the current counter value. Another example shows repeating a basic action:

FOR i = 1 TO 3
  OUTPUT "Hello, future programmer!"
END FOR

Applying and analyzing more complex FOR loops
A sequence like the one shown in this set of pages demonstrates how to read and analyze a loop’s behavior by identifying (a) the loop’s command word, (b) the counter variable, (c) the start and end values, and (d) the code executed on each iteration. In the example where FOR counter = 0 TO 9 and value = counter + 1, the per-iteration outputs are derived from the current counter value plus one. The exercise invites one to construct a table showing counter, value, and output as the loop progresses.

Practice questions and modifications
Several pages present exercises to inspect and modify a given FOR loop:

  • Identify the command word (FOR), the counter variable (e.g., counter), the start (e.g., 0) and end (e.g., 9) values, and the code that runs each iteration (e.g., value = counter + 1; OUTPUT value).
  • Modify 1: Change the loop so the counter starts at 5 instead of 0 (FOR counter = 5 TO 9 …).
  • Modify 2: Change the loop so it outputs numbers 10 to 20 (FOR counter = 9 TO 19 … with the inner code adjusted to output counter + 1, or equivalent adjustment so that the resulting outputs are 10 through 20).

Run-through and analysis examples (Pages 34–39)
A sample run shows a table where the output lists values generated by the loop across iterations, and the investigation section confirms the loop's key components: (a) the counter identifier, (b) the starting value, (c) the ending value, (d) the per-iteration code. For a loop like FOR counter = 0 TO 9 with value = counter + 1 and OUTPUT value, the resulting output sequence is 1, 2, 3, …, 10, corresponding to each iteration’s computed value. Modifying the loop bounds (e.g., starting at 5 or ending at 19) changes the produced sequence accordingly.

The times table algorithm (Page 39)
An example illustrates a loop that computes the product of a user-provided number with integers 1 through 10. The pseudocode reads a numberInput, then iterates count from 1 to 10, computing result = count * numberInput and OUTPUT result. The corresponding table shows numberInput, count, and result for each row. The purpose of this algorithm is to provide the multiplication table for the input number.

Other formats in pseudocode (Page 40)
Pseudocode has several alternate forms beyond the classic FOR … END FOR. Variations include:

  • Replacing END FOR with NEXT counter in some syntax styles.
  • Using a colon after the loop declaration (FOR counter = 0 TO 9:), with subsequent lines treated as inside the loop until a terminator is reached.
  • The RANGE notation (FOR counter IN RANGE (start, end)) where the end value is often exclusive, meaning the loop executes for values from start up to, but not including, end. For example, if the end value were 10 and the end is exclusive, the values would be 0 through 9.

These alternate formats illustrate how indentation, colons, END markers, and range syntax convey the same looping concept across different pseudocode conventions and teaching materials. They also highlight the subtle but important difference: in some variants, the end value is inclusive (the loop runs with the end value included), while in others, the end value is exclusive (the loop stops before reaching end).

Summary of practical takeaways

  • Pseudocode serves as a language-agnostic blueprint for algorithms, focusing on logic rather than syntax.
  • Logic errors arise when the intended outcome is not achieved due to flawed control flow or faulty variable updates.
  • Range checks and inclusivity (e.g., inclusive vs. exclusive bounds) are common sources of off-by-one errors and must be handled explicitly.
  • Correcting pseudocode involves aligning initialization, iteration, and boundary conditions with the intended behavior and ensuring that all branches and edge cases are handled clearly.
  • Loops are powerful for repetitive tasks, but they require careful construction to avoid infinite loops and to ensure the correct number of iterations.
  • The FOR loop is a central example of a count-controlled loop, combining counter, start, and end values into a concise construct, with a predictable iteration pattern and clear exit conditions.

Key LaTeX formulas and numeric references used in these notes

  • Cost discount for group pricing (when number of people > 10):
    cost_per_person = cost_per_person \times 0.9
  • Example costs for horse riding levels (30-minute group lesson):
    level1 = 10.0, \quad level2 = 15.0, \quad level_3 = 20.0
  • Length mapping for 30 or 60 minutes: 30 minutes corresponds to a factor of 1, 60 minutes corresponds to a factor of 2. The final cost before private/group adjustment is:
    cost_before_private = length_factor \times level_rider
  • If the user selects a private lesson, the final cost is doubled:
    cost = 2 \times cost_before_private
  • Inclusive range checks (100–200):
    100 \le number \le 200
  • Example loop structure and outputs (conceptual):
    For a loop counting to 5 with a counter from 1 to 5, outputs follow the pattern:
    "The current count is: " + counter, for counter in {1,2,3,4,5}.

Note: This set of notes aims to consolidate all major and minor points from the transcript into a cohesive, study-ready resource. It covers definitions, examples, corrections, and practical implications related to pseudocode, logic errors, and loops, including how to analyze and modify loops, how to interpret different pseudocode formats, and how to apply these concepts to real-world programming tasks.