Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

A Function in a Loop

Remember the Over the Hill exercise? The dog climbed the hill stair by stair: forward, right, forward, left. At the top, it turned right, and the same four blocks took it down the other side. Now there are two hills, a small one and a big one, with a short valley between them.

The four blocks are needed on all four slopes. Make them a function called zigzag:

  • Define zigzag
    • Move forward
    • Turn right ↻
    • Move forward
    • Turn left ↺

A call is a block like any other, so it can go into a loop. On every pass, the loop calls the function, and the function carries out its four blocks. So this loop takes the dog up two stairs:

  • Repeat 2 times
    • zigzag

Each slope is a loop like this one, with as many passes as the slope has stairs. Without the function, each of the four loops would have to hold all four blocks.

Between the slopes, make the dog face the right way. At the top of a hill, it turns right to face down the slope. At the bottom of the first hill, it walks two tiles along the valley and turns left to face up the next one.

Instructions

  1. 1

    Get the dog over both hills to the goal.

  2. 2

    Use at most 18 blocks.

Back

2/9

  1. 1. Teach the Dog a Trick
  2. 2. A Function in a Loop
  3. 3. A Loop in a Function
  4. 4. Quiz: Calling a Function
  5. 5. Two Functions
  6. 6. A Function That Searches
  7. 7. Fix the Function
  8. 8. Quiz: A Bug in a Function
  9. 9. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.