Loops, iteration, repetition.

Loops are one of the fundamental building block of programming. Loops are used to do a great many things.

A loop is just a bit of code that runs repeatedly. Usually this is a set length, or there is some condition to check. If the condition is met or within a limit, a block of code will be run for each iteration.

There generally is 2 different kinds of loops.

For loop

For loops are done a set number of times. So you need to specify an exact number of times to run. An example:

for 0 to 9 times
    display message "Hello World!"

// This will print the message 10 times. The output of this would look like the below.
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Below is a visual reprisentation of a loop.

While loop

This is the second type of loop. While loops work very similarly to “for” loops, however it does not need a set number of runs. You can run the “while” loop indefinitely.

While loops rather than running a set number of times, it instead will check if a condition is met. If the condition is not met, it will run again. It will do so until the condition is met and stop running.


number count = 0

while count < 10 
    count = count + 1
//This code will run 10 times. As once count reaches 10 it will exit out of the loop.

Just as an aside, you don’t need to worry about creating infinite loops, or breaking your computer etc. You can always reset your computer or close the program. Don’t be afraid to try things!

Now lets see some examples with our pseudo code:

//For loop
for (0 to 4)
    Count each iteration
end

//This count will be 5 as it will count 0, 1, 2, 3, 4
//Remember arrays start at 0  

//We start for the for keyword
//Then use brackets to state the number from which to start and the number to stop at 0 and 4 respectively
//Inside the loop is a block of code to run over and over
//Lastly just for readability the end keyword to stop

//While loop

//We start by giving A the value of 1
number A = 1
number Count = 0 //count is set to 0 so we can count it

//On each iteration it will check if A is not Equal to 5. As long as A is not 5, it will run.
//Each iteration we will add 1 to Count so it will eventually be 5 and stop running
while (A != 5)
    A = A + 1
    Count = Count + 1
end

//The output will be as follows
1 - A is 1 and Count is 1
2 - A is 2 and Count is 2
3 - A is 3 and Count is 3
4 - A is 4 and Count is 4

//The last iteration is not done, as when A is 5, the code is not run because the value is 5.

So it runs 4 times, not 5 times.

Congratulations! You have leveled up in programming!


Next Demystifying Programming – 6 Functions

Previous Demystifying Programming – 4 Conditionals

Leave a Reply

Your email address will not be published. Required fields are marked *