The user should enter a 0 to end the program:
Enter a number ? 4 Enter a number. (Type 0 to stop) ? 2 Enter a number. (Type 0 to stop) ? 3 Enter a number. (Type 0 to stop) ? 0 The sum is 9
Here is the program again:
' Add up numbers that the user enters.
' When the user enters 0, print the sum and end the program.
'
LET SUM = 0
'
PRINT "Enter a number"
INPUT NUMBER
'
DO WHILE NUMBER <> 0
LET SUM = SUM + NUMBER
PRINT "Enter a number. (Type 0 to stop)"
INPUT NUMBER
LOOP
'
PRINT "The sum is", SUM
END
The statements in the loop body have been carefully arranged to do the work properly. This is not an easy thing to get right. Say that the user has just entered 4. Here is how the statements are arranged so that 4 is added to SUM:
DO WHILE
"gatekeeper" tests NUMBER
.LET
statement adds 4 to SUM
.PRINT
statement prompts the user for the next value.INPUT
statement gets the next value, whatever it is
(it could be a 0). The value is stored in NUMBER
.DO WHILE
so that the
"gatekeeper" can test the new value in NUMBER
.
Now everything is repeated with something new in NUMBER
(if the user enters a 0, the DO WHILE
will send
execution to the PRINT
statement after the LOOP
.)
What is the limit on how many numbers can be added up with this program?