|
CLASS NOTES:
SD110 Computer Programming Logic |
|
LOOPS
|
OVERVIEW:
|
WHILE, DO WHILE AND DO UNTIL LOOPS These loops continue to execute until a certain condition occurs to Break them out of the loop. Some Statement within each of these loops much change a Variable to eventually meet the Break condition. While the Flowchat can be identical for these loops, pick the Loop that works for you. Once again you are out to buy toys, and this time you have a lot of
money with you. In this example you will continue to buy toys until you have less than $10 and can no longer afford them. The While loop and the Do While loop accomplish the same tasks with a minor difference in syntax. The Do Until loop also breaks from the loop when the condition is met, but with two notable differences: First, that the loop continues while the Expression remains False (the opposite of the other two which continue while the condition remains True) and that the Do-Until always processes at least once. In the above example what happens if you arrive with less than $10 to begin with? The Do-Until loop would let you buy a toy, change your cash to a negative number, and then Break from the loop. This is an error, so be careful when using Do-Until loops. FOR NEXT LOOPS Another Loop is the FOR-NEXT loop. This type of loop is sometimes referred to as a Definite Loop because you know how many times the loop will repeat. You know this because you set the number within the syntax of the loop itself.
This Loop initially sets the VariableName to 1, then it performs whatever actions are in the DoSomething section, then it increments VariableName by 1 and returns to the top to run again. This Loop will run exactly 100 times before it is done. The default increment is 1, but that can be altered by adding a Step Command to the Loop which lets you manually determine how the VariableName will be incremented, both in how much and in what direction. Q: How many times will each of the FOR-NEXT loops below run? A:
B:
C:
D:
ANSWERS: A: 51 - Runs with the value 0 and all even values up to and
including 100 |