Code is designed to simplify tasks that would have been cumbersome or repetitive. One of the fundamental parts of any program is the ability to deal with repetitive tasks.
Repetition, whereby the result of one operation leads to the next in computer science is known by the term iteration and a single run of a repetitive task is also called an iteration.
Repetition of this form in computer science is achieved with the loop construct. In a loop, the computer repeats a sequence of code over and over until the termination state has been met.
Types of loops
There are many types of loops but the most common loops are without a doubt the while loop and the for loop. In general, these loops are fixed loops and conditional loops.
Both loops have normally got a termination state. A fixed loop will terminate after it has looped the number of times specified whereas a conditional loop will terminate after a condition is no longer satisfied (while) or when a condition is satisfied (do until).
Fixed loops repeat the sequence a certain number of times. This number of times can be hard-coded into the loop or it can be passed through as a variable. The most common type of fixed loop is the for loop as most programming languages feature a style of these.
In YASS this is achieved with the following code:
for ($i = 0, $i < 10, $i++) print($i) end for
This will loop 10 times since the step variable (
$i) starts on 0 and terminates when it reaches 10. The last part of the for loop, the
$i++ part, is the increment expression - this specifies what variable to increment and by how much. The double plus means increment by just one.
A conditional loop is one that will terminate when a condition becomes false or a condition becomes true. There are many variations of the conditional loop, for instance, the while loop will loop whilst a condition evaluates to true (or will terminate when the condition evaluates to false), whereas the do until loop will loop whilst the condition evaluates to false (or will terminate when the condition evaluates to true).
The two types of conditional loops used in the majority of programming languages, including YASS, are the while loop and the do until loop.
The while loop will loop whilst a condition is true. So the simplest while loop, i.e. one that will loop forever or until a break statement is provided, is the
$i = 0 while ($i < 10) print($i) $i++ end while
This loop is, in practice, the same as the for loop shown before.
The other form of loop, the do until loop (or loop until), will loop whilst the condition is false. So the simplest do until loop is the
loop until (false) since this is the non-terminating do until loop.
The following is a simple example of a do until loop in YASS:
$i = 0 loop until ($i == 10) print($i) $i++ end loop
Once again, this will loop ten times.
And that's all there is to loops!