Programming Constructs – Iteration

In programming the word ‘iteration’ is used as the correct technical term for looping or repeating a section of code. It is important to know though that not all loops work in the same way, and we are expected to know which loop to use and when.

Iteration Statements

There are three types of loop that you should be aware of:

FOR

WHILE

DO UNTIL (aka. DO WHILE)

A FOR loop is used when we know how many times we want the code to repeat – this could be because we want it to repeat exactly n times, or because we want it to repeat for each item in a list. To help us do this, we use two types of FOR loop: a Ranged FOR loop and a FOR EACH loop.

Imagine we want to output each item of our list of fruit. This would be best achieved using a FOR EACH loop because the loop will directly access the data. In pseudocode, this would look like:

 

fruit =[‘Banana’, ‘Apple’,’Strawberry’]

FOR EACH piece IN fruit DO

     OUTPUT piece

 

We could do exactly the same with a Ranged FOR loop, but remembering that instead of accessing the data, it uses a ‘stepper’ variable that goes up by 1 each time that the loop repeats:

 

fruit =[‘Banana’, ‘Apple’,’Strawberry’]

FOR i = 0 TO LENGTH(fruit)-1 DO

      OUTPUT fruit[i]

 

In much the same way, the WHILE and DO UNTIL loops are very similar, but have specific differences that we need to be aware of. Unlike FOR loops, you don’t need to know how many times  that the code will be repeated, and because of this these loops run the risk of creating an infinite loop (although in some programs you may actually want to create one).

 

A WHILE loop tests a condition at the top, if the condition is true will run the section of code and continue to do so until the condition is no longer met. In pseudocode, this might look like:

 

Fruit = “”

WHILE fruit <> “banana” DO

   OUTPUT “What fruit is yellow?”

   Fruit = INPUT

 

The DO UNTIL loop will allow the code to run at least once, then tests the condition at the end. If the condition is false, then the loop will repeat.

 

DO

   OUTPUT “What fruit is yellow?”

   Fruit = INPUT

UNTIL fruit = “Banana”

More For Members

Lesson Plan

Coming Soon!

Presentation

Coming Soon!

Homework

Coming Soon!

Not a member yet? Sign Up Here