The sum of the numbers that the user wanted added up will be printed:
How many numbers are to be added ? 3 Enter a number ? 10 Enter a number ? 5 Enter a number ? 2 The sum is 17
The program can be used to add up a list of numbers. But the user first has to count up how many numbers are to be added up. This could be annoying. It would be nice to have a program that keeps adding up numbers until you tell it to stop. Here is a program that does that. The user will enter numbers, one by one, and the program will add each number to SUM. The user tells the program to stop by entering a zero. The zero is how the user "signals" that the program should stop looping.
A sentinel value is a special value that is tested in a DO WHILE
statement to
determine if the loop should end.
The program is not quite finished, yet.
' 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 DO WHILE
statement acts like a gatekeeper.
It allows execution to (re-)enter the loop body
only if the condition is true.
Say that the program has just started.
The user wants to add up a list of numbers.
The first number is 4, so the user enters it:
Enter a number ? 4
Now the program should execute the first statement in the loop body.
Pick a symbol to put in the blank in the program so that the loop body will execute for ANY number the user types except 0. Choose from the available comparisons:
= | equal |
< | less than |
<= | less than or equal |
> | greater than |
>= | greater than or equal |
<> | not equal |