Is there a way to simulate a Repeat/Until loop in a BASIC language without it, and without using a GOTO statement?
For BASIC languages with command separators, can this be done on a single line without an IF/THEN statement?
Retrocomputing Stack Exchange is a question and answer site for vintage-computer hobbyists interested in restoring, preserving, and using the classic computer and gaming systems of yesteryear. It only takes a minute to sign up.
Sign up to join this communityWhat we do is create a FOR/NEXT loop with the special property that we set the STEP rate to zero, so that it will run forever.
To exit the loop, we set the counter equal to the ending value of the FOR loop.
10 FOR X = 0 TO 1 STEP 0
20 INPUT "WHAT IS YOUR NAME?"; X$
30 IF LEN(X$) > 0 THEN X = 1
40 NEXT X
,
For this to work on a single line, the BASIC needs to support boolean values as a number, so that we can use Boolean Math in place of the IF/THEN statement.
Support for this varies from one BASIC to the next, with some having a True value equal to 1 and others with True equal to -1. The following code checks to see which way this works and compensates for it.
10 N = 1 : IF (1 = 1) = -1 THEN N = -1
20 FOR X = 0 TO 1 STEP 0 : INPUT "WHAT IS YOUR NAME?"; X$ : X = (LEN(X$) > 0) * N : NEXT X
(Tested in Apple II Microsoft/FP BASIC).
,
EDIT: An even shorter way to do it, that should be compatible across most BASIC languages, as suggested by Jeff Zeitlin:
10 N=NOT 0 :FOR X=0 TO 1 STEP 0 :INPUT "WHAT IS YOUR NAME?"; X$ :X=(LEN(X$)>0)*N :NEXT X
N = NOT 0
?
Sep 7, 2017 at 19:26
GOTO
in this case is misguided, and that the answer provided relies on a quirky implementation of the FOR
statement.
Sep 8, 2017 at 17:01
GOTO
?GOTO
statement; it is quite possible to write structured code in BASIC usingGOTO
, as in early BASICs, when you don't have constructs such asWHILE...WEND
orREPEAT...UNTIL
. If you understand how those constructs work at a conceptual level, writing equivalent code usingGOTO
is quite understandable, and doesn't rely on questionable misuse of other constructs, such as the submitted answer (FOR...NEXT
withSTEP 0
).GOTO
for branching to more-or-less arbitrary points in the code. It was not unconditionally the use ofGOTO
at any time. However, it has been misread repeatedly, and summarized inaccurately, to the point where it is a cliché, and that is the genesis of my previous comment.GOTO
statement as it has promoted more-structured approaches to control flow that more clearly communicate programmer intention. The issue isn't merely structure, it's comprehensibility. Any successful computer code will have a long maintenance life so costs accrue not just through lack of structure but also from time taken by each new author in discerning the structure. How quickly can you understand a do/while? What about GOTOs that effect a do/while? What about when the loop body is large and loops are nested?