A loop is a control structure designed to repeat a certain chunk of a program over and over again.
Before loops, computer programs were fairly disorganised and difficult to program. The invention of loops meant that computers could really speed up problem solving issues.
Loops in ZPE
ZPE has several different loops, each with advantages over the other:
- For loops
- For each loops
- While loops
- Do until loops
The for loop is the most common type of loop, introduced in version 1.3.0 of ZPE back May 2015 when ZPE started and is the second oldest form of loop in ZPE.
The for loop is given a certain number of times to loop and is known as a fixed loop in programming terms.
The simplest for loop, as well as the most efficient, is shown below:
for ($a = x to y) //Do something here end for
for ($i = 0 to 10) print($i) end for
The above example will loop precisely 10 times starting on 0.
There are many variations of for loops in ZPE as well as many different ways in which to write them. To find out more about the different ways in which to write them look at the official documentation.
For each loops
For each loops iterate an iterable value such as a list or an array. They can also iterate associative arrays and ordered associative arrays. The purpose of such a loop is to make it easier to iterate these kinds of data types.
The following is an example of a for each loop:
$l = [11, 22, 33, 44, 55, 66, 77, 88, 99] for each ($l as $n) print($n) end for
For each of the following, specify how many times each of the following will
for ($i = 2 to 50)
for ($i = -1 to 4)
A while loop is a form of conditional loop that is available in ZPE. It is in fact the oldest loop in ZPE.
While loops will loop when the condition within them evaluates to true. When the condition turns to false they will terminate.
While loops can be written in the same way as they can in other languages such as C or PHP:
$i = 0 while ($i < 20) print($i) $i++ end while
A condition in a while loop can also be a complex condition:
$i = 0 print("Please enter your password.") $password = get_password_input() while ($i < 5 && $password != "password101") print("Incorrect password. Attempt number", $i) print("Please try again.") $password = get_password_input() $i++ end while if ($password == "password101") print("Welcome!") end if
Write a program that asks the user to guess a random number and keeps looping until they
get it right using a while loop. Use
random_numberfunction to generate a random number. More information available here.