Running total within loop algorithm
Different algorithms can be used to keep a running total depending on where the values being totalled come from.
Running total from values in an array
In this example, the numbers to be added together are already held in a 1D array of five integer values, so there is no need to request user input.
Line 1 DECLARE total INITIALLY 0
Line 2 DECLARE numberlist INITIALLY [3, 45, 17, 21, 26]
Line 3 FOR EACH number FROM numberlist DO
Line 4 SET total TO total + number
Line 5 END FOR EACH
Running total from a set number of values input by the user
If the user were to be asked to enter five values one after the other and without need to store the values in an array, the algorithm is as follows.
Line 1 DECLARE total INITIALLY 0
Line 2 FOR loop FROM 0 TO 4 DO
Line 3 RECEIVE number FROM (INTEGER) KEYBOARD
Line 4 SET total TO total + number
Line 5 END FOR
Running total from any number of values input by the user
If the functional requirements created during analysis state that the algorithm should accept any number of values (as opposed to a set number as in the previous examples), then the following algorithm could be used.
Line 1 DECLARE total INITIALLY 0
Line 2 DECLARE decision INITIALLY TRUE
Line 3 REPEAT
Line 4 RECEIVE number FROM (INTEGER) KEYBOARD
Line 5 SET total TO total + number
Line 6 SEND "Do you wish to enter another number" TO DISPLAY
Line 7 RECEIVE decision FROM (BOOLEAN) KEYBOARD
Line 8 LOOP UNTIL decision = FALSE
In this example, the user will have to enter 鈥楾rue鈥 or 鈥楩alse鈥 (perhaps implemented as yes or no).
If they enter 鈥楾rue鈥 the program will ask for another number.
If they enter 'False' the condition on the loop is met and no more values will be entered by the user.