Studyfin Studyfin ✨ Sign up free

Algorithms

Grade 7 · Coding · Free lesson

Hi! I am Studyfin, your coding tutor. Today, we will explore how loops make our algorithms much shorter and smarter!

An algorithm is a step-by-step set of rules to solve a problem. When we write algorithms, we often need to repeat the same action many times.

artificial intelligence

Writing the same instruction over and over makes our code long and hard to read. Instead, we use iteration, which is just a fancy word for a loop.

Looping...

Let us analyze the benefits of loops. They save time, prevent typing mistakes, and let us change our algorithm easily by editing just one number.

100 Lines No Loop 3 Lines With Loop
✏️ Worked example

Analyze how to improve an algorithm that draws a square. The original algorithm has these steps: 1. Move forward 10 steps. 2. Turn right 90 degrees. 3. Move forward 10 steps. 4. Turn right 90 degrees. 5. Move forward 10 steps. 6. Turn right 90 degrees. 7. Move forward 10 steps. 8. Turn right 90 degrees. How can we use iteration to make this algorithm better?

  1. Identify the repeated pattern: We see that 'Move forward' and 'Turn right' are repeated exactly four times.
  2. Count the total lines of code: The original algorithm takes 8 lines of code to write.
  3. Apply iteration: We can wrap the repeated pattern inside a loop that runs 4 times.
  4. Write the new algorithm: 'Repeat 4 times: [Move forward 10 steps, Turn right 90 degrees]'.
  5. Analyze the benefits: The new algorithm is only 3 lines long. It is easier to read, faster to write, and has fewer places to make a mistake.
algorithm
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons