15 Loops

Sometimes the steps of our algorithm need to be repeated until a condition is met.

For example, when we look for primes, we’ll keep on checking different numbers for primeness, but the process each time is the same.  There are essentially three types of loops we might introduce into an algorithm:

  • Repeat a process a given number of times
  • Repeat a process indefinitely (or until the process is stopped manually)
  • Repeat a process until a condition is met

For example, previously we created a program that determined whether or not the scratch cat was on the right.  This only worked when we placed the cat and then executed the code, however if we want the program to keep on checking as we move the cat around, we can put in a loop that will keep on checking until we end the program.

left: when green flag is clicked, if x position is less than 0 then say I'm on the right for 0.5 seconds. Right - same sequence, except the sequence is repeated forever

Image: screenshots from Scratch

Let’s have a look at some other examples in Scratch

Transcript

Loops involving if-then statement

Transcript

Coding

Create a program in Scratch that

  1. includes user input and a loop.
  2. includes a loop that uses an if-then statement.

License

Icon for the Creative Commons Attribution-NonCommercial 4.0 International License

Mathematical Reasoning and Investigation Copyright © 2023 by Deakin University is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License, except where otherwise noted.

Share This Book