Structured Programming4. Loops |
|
Join the DiscussionMore of this FeatureTutorialsLoops allow for the same statement to be executed a number of times in succession. There are three different loop constructs that can be used depending on whether the number of repetitions is known and also (where the number of repetitions is not known and is dependent on a condition) whether the loop is allowed to be bypassed if the termination condition is met before the loop is first executed. For
A for loop allows a statement to be executed a specified number of times. The for loop begins with a loop control variable assigned a specific initial value. This control variable in then incremented (or decremented) by a specified amount each time around the loop until a specified terminating value is reached at which time the statement following the loop is then executed. pseudo code
for (initial-value, final-value, increment)
statement-1 example
for (a = 3, a > 12, a = a + 2)
print a This example will output 3 5 7 9 11. While
A while loop allows a statement to be executed until a given condition is met. If the condition is met prior to executing the loop then the loop will not be executed. As soon as the condition is met, execution continues with the statement following the loop. pseudo code
while not condition
statement-1 example
while not end-of-file
{ read record write record } Until
An until loop also allows a statement to be executed until a given condition is met but the condition will not be tested until after the loop has been executed once. Once the condition is met the statement following the loop will be executed. pseudo code
do
statement-1 until condition Note that this article is copied from the "Ask Felgall" website with the permission of the copyright owner. |


