Use pseudocode to write: a ''post-condition'' loop

Resources | Subject Notes | Computer Science

A-Level Computer Science - 11.2 Constructs - Post-Condition Loops

A-Level Computer Science - 11.2 Constructs

Post-Condition Loops

A post-condition loop is a type of loop where the condition is checked after each iteration of the loop body. This means the loop body will always execute at least once, regardless of the initial value of the loop control variable. This is in contrast to a pre-condition loop, where the condition is checked before each iteration.

In pseudo-code, a post-condition loop is typically written using the `while` keyword. The condition is placed at the end of the loop statement.

Pseudo-code Example

Consider the following example: We want to repeatedly ask the user for a positive number until they enter one. The loop continues after the user has entered a number.

Step Pseudo-code Explanation
1 \begin{small>while (number <= 0)
display "Please enter a positive number:"
read number
}
The loop continues as long as the entered number is less than or equal to zero. Inside the loop, a message is displayed prompting the user for input, and the entered number is read.
2
display "You entered: " + number
Once a positive number is entered, the condition becomes false, and the loop terminates. The entered number is then displayed.

Example with a Specific Task

Let's say we want to calculate the factorial of a non-negative integer using a post-condition loop.

The factorial of a non-negative integer n, denoted by $n!$, is the product of all positive integers less than or equal to n. Mathematically, $n! = n \times (n-1) \times (n-2) \times ... \times 2 \times 1$.

Here's the pseudo-code:

Step Pseudo-code Explanation
1 \begin{small>integer factorial = 1
integer n = input number
while (n > 0)
factorial = factorial * n
n = n - 1
display "Factorial of " + n + " is " + factorial
}
The `factorial` variable is initialized to 1. The user is prompted to enter a number `n`. The loop continues as long as `n` is greater than 0. Inside the loop, the `factorial` is updated by multiplying it with the current value of `n`, and then `n` is decremented. Finally, the calculated factorial is displayed.

This example demonstrates how a post-condition loop can be used to repeatedly perform a task until a certain condition is met. The loop ensures that the calculation continues until the input number becomes zero.