Resources | Subject Notes | Computer Science
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.
The general structure of a pre-condition loop in pseudo-code is as follows:
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 |
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:
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.