The DO … LOOP is used to repeat a block of statements while a condition is true OR until a condition becomes true.

This type of loop is required when you don’t know how many repetitions you will need before you start.

When you know the number of repetitions,

you use a FOR .. NEXT loop.

There are 5 possible structures for DO Loops

DO WHILE (condition ) DO UNTIL (condition )

Statements                              Statements

LOOP                                       LOOP

——————————————————————————-

DO                             DO

Statements      Statements

LOOP WHILE (condition ) LOOP UNTIL (condition )

DO

Statements

If ( condition) then exit do

LOOP

In a DO WHILE or LOOP WHILE, the structure will be executed repeatedly, as long as the condition is true.  When the condition is no longer true, the compiler will move to the line of code after LOOP.

In a DO UNTIL or LOOP UNTIL, the structure will be executed repeatedly, as long as the condition is not true.  When the condition becomes true, the compiler will move to the line of code after LOOP.

When might you use a DO.. LOOP?

A user wants to continue entering numbers and have the  computer count how many were entered.  Stop when the user enters a “-1”.

Possible Code:

CLS

DIM num AS INTEGER, count as integer

count = 0

DO

INPUT “Please enter a number “, num

count = count + 1

LOOP UNTIL num = -1

count = count – 1     ‘don’t want to include -1 in the count

PRINT USING “You entered ### numbers”; count

———————————————————–

CLS

DIM num AS INTEGER, count as integer

count = 0

INPUT “Please enter a number “, num

DO WHILE num <> -1

count = count + 1

INPUT “Please enter a number ”,num

LOOP

count = count – 1

PRINT USING “You entered ### numbers”; count

———————————————————-

CLS

DIM num AS INTEGER, count as integer

count = 0

DO

INPUT “Please enter a number ”,num

If num = -1 then exit do

count = count + 1

LOOP

PRINT USING “You entered ### numbers”; count

author avatar
William Anderson (Schoolworkhelper Editorial Team)
William completed his Bachelor of Science and Master of Arts in 2013. He current serves as a lecturer, tutor and freelance writer. In his spare time, he enjoys reading, walking his dog and parasailing. Article last reviewed: 2022 | St. Rosemary Institution © 2010-2024 | Creative Commons 4.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment