|
Loops allow for a piece of code to be repeated many times. This is very useful as there are many
situations where it is necessary to repeat the same code a certain number of
times or until a condition is met. Loops are used where it is impractical
or time consuming to write the code out completely.
In general there are three different types of loops:
Repeat Loops : a certain bit of code is repeated until a condition is met.
Example
X = 3
Repeat
X = X + 1
Until X > 5
Write(X)
Using this code one will be added to X each time the loop is executed. If X is bigger than 5 then the loop will end and whatever code is next will be executed. In this case six (the value of variable X) will be written onto the screen.
While Loops : code is repeated while the conditions stated are met.
Example
X = 3
While X < 5
Do X = X + 1
Write(X)
In this case one will be added to X as long as X is smaller than five.
The final value of X is five. When the loop ends all the code that comes
after the loop will be executed. The main difference
between a while loop and a repeat loop is that with the repeat loop all code is executed once.
Whereas with the while loop this will not happen.
For Loops : the code is repeated a certain number of times. The number of
the loop is stored in a variable specified in the loop code.
Example
For Y = 1 To 3
Do X := Y + 2
The value of Y will change with each cycle of the for loop.
The first time the loop runs through the value will be one.
The last time the loop runs the value will be 3. The final value of X will be 5.
For loops are useful because they will always repeat a set number of times.
|