AQA Computer Science GCSE
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:
# outputs 1, then 2, then 3
Using a variable is similar.
FOR i <- 0 TO LEN(anArray) – 1
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.
# 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:
for i in range(0, len(theWord)):
# 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 - which is the final a of banana.