That Blue Square Thing

AQA Computer Science GCSE

24 March 2020: as the position regarding GCSE exams is now a bit clearer, I've decided to stop adding updates to the revision pages.

Programming Concepts - Repetition

Definite Repetition - FOR loops

Definitive repetition repeats a block of code a set number of times. You know in advance how many times the block will be repeated - either based on a value or a variable.

Use this when you know in advance how many times you want to loop, including when you want to loop through every value in a string or array.

In programming this is implemented using a FOR loop.

The pseudocode options for this are shown below:

FOR i <- 1 TO 3
OUTPUT i
ENDFOR

# outputs 1, then 2, then 3

Using a variable is similar.

FOR i <- 1 TO diceThrow
# works from 1 to the value of the variable
ENDFOR

FOR i <- 0 TO LEN(anArray) – 1
# works from 0 to the length of the array minus 1
ENDFOR

Note that in pseudocode a FOR loop starts at the first value and works all the way to the end value.

This works slightly differently Python.

for i in range(1, 4):
print(i)
# prints 1, 2, 3

Note that Python starts at the first value and works as far as the end value, but doesn't include the end value. This is awkward and annoying, but just one of those things you need to deal with.

This is slightly easier to use when iterating over a string or array:

theWord = "banana"
for i in range(0, len(theWord)):
print(theWord[i])
# prints b, a, n, a, n, a

This works because arrays and strings are indexed from 0. So, the loop starts at 0 and goes as far as the length of theWord (6) minus 1. This takes it as far as theWord[5] - which is the final a of banana.

Note that I've used i as my loop variable each time. This is something programmers often do - i probably stands for index. It's a really common thing to do. You don't have to do it, but any programmer looking at your code will automatically know what i means.
If you need two different loop variables for FOR loops then using i and j is standard.