DO LOOPS
Up until this point if we wanted to print out a variable, or do a calculation we would need to write it over and over again. Loops allow us to do the same calculation until a condtion is met. The dowhile loop is common to many languages and its algorithm usually goes something like:
X = 0 DOWHILE X <> 5 X=X+1 LOOP |
What that does is takes X and initializes it to 0. Then we make the loop run until X = 5. The X=X+1 is called a counter. What this does is count the number of times the loop goes around. If X was initialized to 5 off the bat, then the program would skip to the line right past LOOP, because it kind of works like an IF statement in that it will check to see if X=5 and if it isn’t then it will loop. The 5 is actually called a sentinel value, or value that causes the loop to stop.
REPEAT UNTIL
Similarly we can use a different form of loop. The REPEAT UNTIL loop checks for the sentinel value at the bottom of the loop. So if we did something like:
X = 5 Repeat X=X+1 Until X <>5 |
The result would be an infinite loop. Why you ask? Because X is being initialized to 5. It runs through the loop once because it only checks at the bottom of the loop, and because we increment X to 6, the loop will continue to run indefinitely because 5 will never be reached since all we are doing is incrementing it.
FOR NEXT
FOR NEXT loops are used when you know how many times you want the loop to run. Say you want the loop to run only 3 times, you would use a FOR NEXT loop, over the others because FOR NEXT loops have built in capabilities that don’t require outside counting. The algorithm for FOR NEXT loops is:
Name=”John Smith”FOR X = 1 TO 5 print Name Next X |
Again the print is commonly used for displaying information to the screen, in this case it will print out John Smith 5 times. The 1 TO 5 is saying that X, a normal variable will be initialized to 1 and everytime it hits the NEXT command, will increase by 1.
ENDS
Now say you are getting information from a user, and if the user enters a -1 as a value, you want the loop to end, but if not then you want it to keep going. To do this you will need the END and the form of loop. END DO, END FOR, and END REPEAT are all perfectly fine algorithms for popping out of loops when the sentinel value is entered. For example:
DO INPUT “Enter the student grade” INTO X IF X = -1 THEN END DO ENDIF LOOP |
TOTALLING
It isn’t uncommon for programs to use totalling techniques. The easiest way to total in a loop is to use the variable1 = variable1 + Variable2. Let’s use the previous example and look at it:
DO INPUT “Enter the student grade” INTO X IF X = -1 THEN END DO ELSE Total = Total + X ENDIF LOOP |