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

Resources | Subject Notes | Computer Science

A-Level Computer Science - 11.2 Constructs - Pre-Condition Loop

A-Level Computer Science - 11.2 Constructs

Pre-Condition Loops

A pre-condition loop is a type of loop where the condition is checked before each iteration of the loop body. If the condition is false initially, the loop body is never executed. This is useful when the loop needs to run only if certain conditions are met before starting.

Pseudo-code for a Pre-Condition Loop

The general structure of a pre-condition loop in pseudo-code is as follows:

  1. Check the pre-condition.
  2. If the pre-condition is true, then execute the loop body.
  3. While the pre-condition remains true, repeat the loop body.
  4. If the pre-condition becomes false, exit the loop.

Here's an example of a pre-condition loop in pseudo-code:

Step Pseudo-code
1. Pre-condition Check Check (condition)
2. If Condition is True If (condition) then
3. Loop Body { ... loop body statements ... }
4. Repeat Repeat
5. Condition Update Update (condition)
6. Condition Check (Loop Continuation) Go to step 1

Example: Validating User Input

Consider a scenario where we want to repeatedly ask the user for input until they provide a valid number greater than zero. A pre-condition loop is suitable for this.

Here's the pseudo-code for this example:

Suggested diagram: A flowchart showing a loop that continues until the user enters a number greater than zero.
Step Pseudo-code
1. Get User Input Get user input as number
2. Pre-condition Check If (number > 0) then
3. If Condition is True { ... }
4. Display Success Message Display "Valid input: " + number
5. Exit Loop Exit loop
6. If Condition is False Else
7. Display Error Message Display "Invalid input. Please enter a number greater than zero."
8. Repeat Repeat

In this example, the loop will only execute if the user's input is greater than zero. If the input is not valid, the loop will continue to prompt the user until a valid number is entered.