Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.3Loops

Part 4.3Loops

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:

  1. For loops
  2. For each loops
  3. While loops
  4. Do until loops

For 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:

YASS
for ($a = x to y)
  //Do something here
end for

For example:

YASS
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:

YASS
$l = [11, 22, 33, 44, 55, 66, 77, 88, 99]
for each ($l as $n)
  print($n)
end for
  1. For each of the following, specify how many times each of the following will loop:
    1. for ($i = 2 to 50)
    2. for ($i = -1 to 4)

While loops

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:

YASS
$i = 0
while ($i < 20)
  print($i)
  $i++
end while

A condition in a while loop can also be a complex condition:

YASS
$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

  1. 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 the random_number function to generate a random number. More information available here.
Feedback 👍
Comments are sent via email to me.