Higher High Level Language Constructs

Page 15

Repetition Conditional Loops The fixed loop is limited in that the programmer has to know in advance how many times the program has to go round the loop. The conditional loop is a more flexible loop structure and is used when the number of times a section of program is repeated is not known beforehand, and depends on a certain condition being met. There are two kinds of conditional loop, one with the condition at the end of the loop, the other with the condition at the start of the loop. DO .. LOOP WHILE (In some languages REPEAT .. UNTIL) The DO .. LOOP WHILE structure is a conditional loop in which the condition comes at the end of the loop. The general structure of a do‌..until loop is shown below. DO execute commands LOOP WHILE some condition is true Notice that in this structure, the condition is at the end of the loop. This means that the steps inside the loop must be executed at least once. Example 4.5:- This algorithm makes use of a sentinel value. A sentinel value is used to tell the loop when to stop. In this example the sentinel value is the string 'banana'. This program will keep asking for name until Banana is entered. Algorithm 1. 2. 3. Program

start loop get password until the password is Banana

DO PRINT"Please enter the correct password" INPUT password$ LOOP WHILE password$<>"Banana"

Example4.6 This example is the same as the one above except it mixes conditional and unconditional repetition by only allowing 3 attempts. Algorithm

1. 2. 3. 4. 5. 6.

set counter to 0 start loop add 1 to counter get password until counter = 3 OR password is banana display total

Program

LET counter=0 DO LET counter=counter+1 PRINT"Please enter the correct password" INPUT password$ LOOP WHILE password$<>"Banana" AND counter<>3

Higher Computing - Soft dev – High Level Language Constructs Produced by S Lambert, R Simpson and HSDU for The City of Edinburgh Council, 2004

Infosheet 5.3


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.