Jugami Code Club

Jugami › Code Club › Algorithms and Loops

Code Club · Unit 1 · grades 6–8

Algorithms and Loops

How to give instructions so exact that even a robot can’t get them wrong, and how to say “do that again” without writing it 100 times.

You already follow algorithms every day. A recipe is one. So are the directions to a friend’s house, and the way you tie your shoes. In this unit you’ll learn to write them for a computer, which is a lot pickier than your friends are.

First you’ll learn what an algorithm is and why order and precision matter. Then you’ll meet loops, the trick that lets a short program do a lot of work. Finally you’ll learn the true story behind the famous moth “bug” of 1947. Then it’s your turn: steer Loop Bot through six puzzles, hunt some bugs, and take the quiz.

A green robot at the top of a copper staircase path on a grid, beside a program: repeat 4 times, forward, turn left, forward, turn right repeat 4 { forward turn left forward turn right } > 5 blocks instead of 16. Nice.

01What is an algorithm?

An algorithm (say it “AL-guh-rith-um”) is a list of steps that solves a problem or gets a job done. If you follow the steps in order, you get the result, every time.

Algorithms are everywhere, not just inside computers:

  • A recipe is an algorithm for pancakes.
  • Directions (“turn left at the library, then go two blocks”) are an algorithm for getting somewhere.
  • Long division is an algorithm for dividing big numbers. You learned it in school!
  • Searching for a word in a dictionary is an algorithm, too: open near the middle, check if your word comes before or after, and keep going.

A program is an algorithm written in a language a computer can follow. The person who writes it is a programmer. That’s you, by the end of this page.

Did you know? The word “algorithm” comes from a person’s name. About 1,200 years ago, a scholar named Muhammad ibn Musa al-Khwarizmi worked at the House of Wisdom in Baghdad (in today’s Iraq). He wrote a book explaining how to calculate with the digits 0 to 9, the same digits we use now.

His original Arabic book is lost, but a Latin version survived under the title Algoritmi de numero Indorum, roughly “Al-Khwarizmi on the Hindu art of reckoning.” His name, written in Latin as “Algoritmi,” slowly turned into our word “algorithm.” Another of his books gave us the word “algebra.”

02Sequence: order matters

Sequence means the order of the steps. A computer always runs steps in the exact order you wrote them, from top to bottom. Swap two steps and you can get a very different result.

Getting dressed: works

  1. 1. put on socks
  2. 2. put on shoes
  3. 3. tie laces

Getting dressed: oops

  1. 1. put on shoes
  2. 2. put on socks
  3. 3. tie laces

Same three steps, different order, and now your socks are on top of your shoes. When a program does something strange, one of the first things to check is the order of the steps.

03Be precise

Ask a friend to “go to the door” and they’ll figure it out. A computer can’t fill in gaps. It does exactly what you say, nothing more and nothing less. So instructions for a computer have to be precise: clear, exact, and impossible to misread.

“Turn” isn’t precise. Turn which way? How far? “Turn right 90 degrees” is. That’s why the robot in our game only knows three moves, each one exact:

forward
Move one square in the direction you’re facing. If a wall is in the way, bonk: the program stops.
turn left
Spin a quarter turn to the left, staying on the same square.
turn right
Spin a quarter turn to the right, staying on the same square.

Here’s the tricky part: “left” and “right” are from the robot’s point of view, not yours. If the robot is facing down the screen, its left is your right. Try standing up and turning with it. Programmers really do this!

04Loops: do it again

Say you want the robot to walk around a square, two steps on each side. Written out in full, that’s 12 blocks:

Without a loop: 12 blocks

  1. forward
  2. forward
  3. turn right
  4. forward
  5. forward
  6. turn right
  7. forward
  8. forward
  9. turn right
  10. forward
  11. forward
  12. turn right

With a loop: 4 blocks

  1. repeat 4 {
  2. forward
  3. forward
  4. turn right
  5. }

Count the blocks: repeat is one block, and the three blocks inside it make four.

A loop tells the computer to run some steps more than once. The repeat 4 block means “do everything inside me 4 times.” The steps inside are called the loop body. Each time through is called an iteration.

Why loops save work

  • Less to write. Walking 100 squares forward takes 100 blocks without a loop, or 2 blocks with one: repeat 100 { forward }.
  • Fewer mistakes. The fewer blocks you write, the fewer places a typo can hide.
  • Easy to change. Want a bigger square? Change one number instead of rewriting a dozen lines.

Loops inside loops

You can put a loop inside another loop. This is called nesting. Look at the square again: each side is “forward, forward,” which is itself a pattern. So the square can be repeat 4 { repeat 2 { forward } turn right }. The inner loop runs 2 times for every 1 time the outer loop runs, so forward happens 4 × 2 = 8 times.

Try it in your head: how many times does the robot move in repeat 3 { repeat 5 { forward } }? (Answer: 3 × 5 = 15.)

05Spotting patterns

The real skill with loops is noticing when something repeats. Programmers call this pattern recognition. Here’s a way to do it:

  1. Write out the steps the long way first, or say them out loud.
  2. Look for a chunk that shows up again and again. That chunk is your loop body.
  3. Count how many times the chunk repeats. That’s your number.
  4. Check the leftovers. Steps before or after the pattern go outside the loop.

For example, climbing a staircase is “forward, turn left, forward, turn right” for every step. Four steps? repeat 4 { forward, turn left, forward, turn right }. That’s 5 blocks instead of 16.

06A first look at “if”

So far, our robot follows its program blindly. But what if it could check something first? That’s a conditional: a step that only happens if something is true.

  1. if there is a wall ahead {
  2. turn right
  3. } otherwise {
  4. forward
  5. }

You use conditionals all the time: if it’s raining, take an umbrella. Put that “if” inside a loop and the robot can find its way through a maze it has never seen. Loop Bot doesn’t have “if” blocks yet. You’ll get them in the next Code Club unit, Conditionals.

07Debugging and the famous moth “bug”

A bug is a mistake in a program that makes it do the wrong thing. Debugging means finding and fixing it. Every programmer, even the best, spends a lot of time debugging. Here’s a good method:

  1. Run it and watch what actually happens.
  2. Compare that with what you wanted. Where did it first go wrong?
  3. Step through one block at a time to find the exact block. (Loop Bot’s Step button does this.)
  4. Fix one thing, then test again.

The moth in the machine

On September 9, 1947, a team at Harvard University was testing a huge computer called the Harvard Mark II. It didn’t use chips. It used relays, little electric switches that clicked open and shut.

When the machine had trouble, the team went looking. Stuck inside Relay #70 on Panel F, they found a real moth. They pulled it out and taped it into the machine’s logbook with a note. The entry, at 15:45 (3:45 in the afternoon), reads:

“Relay #70 Panel F (moth) in relay.
First actual case of bug being found.”

Our drawing of a logbook page: lined paper with the handwritten note 1545 Relay #70 Panel F (moth) in relay, First actual case of bug being found, and a moth held down by a strip of tape 1545Relay #70 Panel F (moth) in relay. First actual case of bug being found.
Our own drawing of the famous logbook entry, not the real page. The real logbook, with the actual moth still taped inside, belongs to the Smithsonian’s National Museum of American History in Washington, D.C.

See the joke? It says “first actual case” of a bug. The team already called machine problems “bugs.” This time, for once, the bug was a real insect.

Where does Grace Hopper fit in?

Grace Hopper was a mathematician and U.S. Navy officer who worked on the Harvard Mark I and Mark II computers. She went on to become a well-known computer pioneer: she built one of the first compilers (programs that translate human-friendly code into machine code) and helped create the programming language COBOL. She retired from the Navy as a rear admiral at age 79.

The moth story is often told as “Grace Hopper found the first bug,” but that’s not quite right:

  • She didn’t find the moth herself. The Smithsonian says engineers on the Mark II team found it, and that the logbook was probably not Hopper’s. She loved telling the story, though, and she helped make the words “bug” and “debug” famous.
  • She didn’t invent the word “bug.” Engineers had called small flaws in machines “bugs” since the 1800s. The inventor Thomas Edison wrote about “bugs” in his inventions in letters in 1878.

How do we know? The logbook itself survived. In 1988 it was at a Navy computer museum in Dahlgren, Virginia, and today it is in the Smithsonian’s collection. Hopper later recalled, in a 1981 article, that it happened in 1945. But in a 1998 article, Smithsonian historian Peggy Kidwell used the logbook and the Mark II records to date the page to September 9, 1947. Memories fade; records like this help us check.

08Play Loop Bot

How to play: Build a program from blocks to steer the robot to the green flag. Some levels also have gold gems to collect first. Press Run to watch, or Step to go one block at a time.

New blocks go where the blinking ▮ insert here marker is. Click any block in your program to move the marker just after it. Click + inside this loop to add blocks into a repeat. Change a loop’s number with its − and + buttons.

Scoring: ★ solve the level · ★★ solve it using a loop · ★★★ use a loop and stay at or under the block target. Your best score for each level is saved only in this browser.

Keyboard: F forward · L turn left · R turn right · P add a repeat · 2–9 set the repeat number · Backspace delete the block before the marker · G run · S step · T try again. Tab moves between buttons. Tab to “+ inside this loop” or “+ at the end” and press Enter to move the marker.

The six levels

  1. Hello, robot. Drive straight to the flag. Target: 2 blocks.
  2. Turn the corner. Go down a hallway, turn, and reach the flag. Target: 5 blocks.
  3. Around the block. Collect three gems on the corners of a square and return to the start. Target: 4 blocks (hint: a loop inside a loop).
  4. Staircase. Climb four steps to the top. Target: 5 blocks.
  5. Castle wall. Climb three towers for their gems and come back down each time. Target: 9 blocks.
  6. Mow the lawn. Sweep back and forth across a 5 × 4 lawn to collect all 20 gems. Target: 11 blocks.

09Find the bug

Each program below has exactly one buggy line. Read the goal, trace the program in your head (or with your finger), and click the line you think is wrong.

Bug 1: The short walk

Goal: walk exactly 5 squares forward to reach the flag.

Show the answer

The bug is repeat 4. The robot only walks 4 squares and stops one short. It should be repeat 5.

Bug 2: The square that wasn’t

Goal: walk around a square, 3 squares on each side, turning right at each corner.

Show the answer

The bug is turn right: it’s outside the loop, so it only happens once, at the very end. The robot walks 12 squares in a straight line (or bonks into a wall). Move turn right inside the loop, right after the third forward.

Bug 3: The staircase spiral

Goal: the robot starts facing right (east). Climb a staircase that goes up and to the right: one square right, one square up, four times.

Show the answer

The bug is the second turn left (line 5). After stepping up, the robot faces north. Turning left makes it face west, so it walks in a little square instead of climbing. It needs turn right to face east again.

Bug 4: Not precise enough

Goal: go forward 2 squares, turn right, then go forward 1 square. This is written for a robot that only understands forward, turn left, and turn right.

Show the answer

The bug is turn. Turn which way? The robot can’t guess. It should say turn right. Instructions for a computer have to be precise.

10Quiz

1. What is an algorithm?

2. The word “algorithm” comes from…

3. A robot faces east. It runs: turn left, turn left, forward. Which way did it move?

4. How many times does the robot move forward in repeat 3 { forward, forward, turn right }?

5. Which is the best reason programmers use loops?

6. How many forward moves are in repeat 2 { repeat 3 { forward } }?

7. Why is the Harvard Mark II logbook page from September 9, 1947 famous?

8. What does “debugging” mean?

9. A program says: if there is a wall ahead, turn right; otherwise, go forward. The robot is facing a wall. What does it do?

11Talk About It

There are no single right answers here. Talk with a friend, your class, or a grown-up.

  • Write the algorithm for something you do every morning. Could someone else follow it exactly? Where might they get confused?
  • In Loop Bot, was the shortest program always the easiest one to understand? When might a longer program be better?
  • Where do you see loops in real life? Think about music, sports practice, or the seasons.
  • The moth story is often told wrong: people say Grace Hopper found it, or that it’s where the word “bug” came from. Why do you think simple versions of stories spread more easily than the true ones?
  • Al-Khwarizmi wrote his books about 1,200 years ago, long before computers. Why do you think his name ended up in a computer word?

12Sources and credits

  1. Smithsonian, National Museum of American History, “Log Book With Computer Bug” (object nmah_334663, ID 1994.0191.01): describes the 1947 Mark II moth, the “first actual case of bug being found” label, that the log book was probably not Hopper’s, and Edison’s use of “bug” in the 1870s. americanhistory.si.edu: object nmah_334663
  2. U.S. Naval History and Heritage Command, photograph NH 96566-KN, “The First ‘Computer Bug’”: moth found in Relay #70, Panel F, of the Mark II Aiken Relay Calculator during testing at Harvard, 9 September 1947. history.navy.mil: NH 96566-KN
  3. Peggy Aldrich Kidwell, “Stalking the Elusive Computer Bug,” IEEE Annals of the History of Computing 20, no. 4 (1998): 5–9. Dates the logbook page to 9 September 1947 and notes the “1545” time and Hopper’s 1981 recollection of 1945. doi.org/10.1109/85.728224
  4. U.S. Naval History and Heritage Command, “Rear Admiral Grace Hopper” (namesake biography): Navy service, work on the Mark I and Mark II at Harvard, compilers, COBOL, retirement in 1986 at age 79. history.navy.mil: Grace Hopper
  5. Smithsonian, National Museum of American History, “Grace Hopper: The Navy and Computers.” americanhistory.si.edu: Grace Hopper
  6. J. J. O’Connor and E. F. Robertson, “Al-Khwarizmi,” MacTutor History of Mathematics, University of St Andrews: the House of Wisdom, Algoritmi de numero Indorum, and the origins of “algorithm” and “algebra.” mathshistory.st-andrews.ac.uk: Al-Khwarizmi
  7. Alexander B. Magoun and Paul Israel, “Did You Know? Edison Coined the Term ‘Bug’,” IEEE Spectrum, 1 August 2013: Edison’s 1878 letters about “bugs.” (Despite the headline, the word was already shop slang; see source 1.) spectrum.ieee.org: Edison and “bug”

Credits. Written for jugami.com by Grace, the Jugami Code Club teacher. The robot, game boards, logbook drawing, favicon and share images are original art made in code (hand-written SVG) for this page; the logbook drawing is our illustration, not a copy of the real page. Loop Bot runs only in your browser. It saves your best stars in this browser’s local storage and sends nothing anywhere.