KS3 Computing/Iteration
Iteration
editIteration (looping) is a way of repeating a specific chunk of code several times. It might be a specific number of times, e.g. 10, or it might be until a certain condition is met.
For example, if you want to repeat a phrase 3 times, you could do:
for x in range(3):
print("Time for holidays!")
This is called a for loop and would output the following:
Time for holidays! Time for holidays! Time for holidays!
Types of loops
editThe different types of loops include those that:
- Repeat n times - where n is the number of times the code is executed
- Repeat until - where the code is repeated until a certain condition is true/false
- Repeat forever - where the code is repeated continuously until the end of the program
Loops in Python include:
for while
Loops in Scratch include:
repeat forever
Introducing the concept of looping
editIt is a good idea to let younger students write long sections of code first, then ask them how they might reduce the number of lines of code / make their code more 'efficient' (answer = by introducing a loop!).
A simple example of this would be asking them to print out the 3 times tables.
At first they would manually print out all parts, e.g. print("1x3=3") written out 12 times.
Once they have done this, show them how a loop can get the program to do all the hard work!
Example code in Python would be:
for n in range(1,12):
print(n,' x 3 = ',i*n)
Here is an example of introducing loops in Scratch