Skip to content

← Grade 6 Computing

Algorithms: Step by Step

Unit 3 · Algorithms and programming

Hide the stories, facts, photos, activities and interactives, for revising before an exam
In this unit 11 sections
  1. What is an algorithm?
  2. Clear and exact
  3. Sequence: the right order
  4. Directions to Nyatapola
  5. Repetition: doing it again
  6. Choices: if this, then that
  7. Remembering things: variables
  8. Does it work? Checking an algorithm
  9. Bugs and debugging
  10. In short
  11. Exercise

A visitor stops you outside your school and asks the way to Nyatapola. You say, “Go up the road and turn left near the temple.” Which road? Which temple? How far up? The visitor can ask you, or look around and guess. A computer can do neither. It does exactly what it is told, in exactly the order it is told, and nothing else.

So before you can tell a computer what to do, you have to learn to give instructions so clear that nothing can go wrong. In this unit you will do that without a computer at all: with chiya, with streets, and with a tea shop’s bill. You will write instructions, follow them exactly like a machine, find the mistakes in them, and fix them. In Unit 4 you will give the same kind of instructions to a computer.

What is an algorithm?

Think of making chiya. You don’t do it any old way: water and milk in the pot, tea leaves, sugar, boil, strain into a cup. Anyone who follows those steps, in that order, gets chiya.

A list of steps like that, which does a job or solves a problem, is called an algorithm. Each step is an instruction. A good algorithm has three things:

  • every step is clear and exact, with only one meaning;
  • the steps are in the right order;
  • it comes to an end, and when it ends, the job is done.

You follow algorithms every day. A recipe is one. So are the steps to wash your hands properly, to tie a shoelace, to pay a bill on a phone, and the way a bus conductor collects fares, stop after stop. Your teacher follows one to do a long division on the board.

Computers follow algorithms too. In Unit 1 you saw that a computer follows a program: a program is an algorithm written in a way a computer can carry out. Every app on a phone is built from them: the steps that put a photo on the screen, find a word in a message, or work out the shortest way across a city. A computer is very fast and never gets tired, but it only follows its algorithms; it can’t make one up for itself. People write them.

Two pages of an old Arabic manuscript, handwritten in black and red ink, with diagrams made of squares
Figure 3.1 Two pages from a copy of al-Khwarizmi’s book on algebra, made in 1342 and kept in the Bodleian Library in Oxford. Photo: Bodleian Library, University of Oxford, Public domain

Which of these is an algorithm?

Pick an answer to see why.

Clear and exact

Here is how a grandmother might tell you to make chiya:

Boil some water and milk, put in the tea, add sugar, and let it boil till it’s done.

You could follow that, because you have seen chiya made. You would guess how much water, how much tea, and when it is “done”. But give it to someone who has never made chiya, and they would have to ask a lot of questions. How much is “some”? Which tea, leaves or a tea bag? How much sugar? How long is “till it’s done”?

A computer can’t ask and can’t guess. So an algorithm for a computer has to answer every one of those questions before it is asked:

  1. Pour 1 cup of water and 1 cup of milk into the pot.
  2. Turn the stove on.
  3. Add 2 spoons of tea leaves and 2 spoons of sugar.
  4. Boil for 3 minutes.
  5. Turn the stove off.
  6. Strain the chiya into 2 cups.

Every amount is a number, every step is one action, and nothing is left for the reader to work out. Being precise means being exact like this: each instruction has only one meaning.

A drawing of a spacecraft with a large solar panel, flying above the reddish surface of Mars
Figure 3.2 An artist’s picture of the Mars Climate Orbiter at Mars (NASA). Photo: NASA/JPL/Corby Waste, Public domain

Which instruction is precise enough for a robot?

Pick an answer to see why.

Sequence: the right order

The steps of an algorithm are done one after another, in order, from the first to the last. This is called sequence. The order matters: “strain the chiya, then boil it” uses the same two steps as “boil the chiya, then strain it”, but only one of them gives you hot chiya.

Some steps can swap places without any harm: it doesn’t matter whether the tea leaves or the sugar go into the pot first. Others can’t: the boiling must come after everything is in the pot, and the straining after the boiling.

Try it

Make the robot’s chiya

This robot makes chiya, but it does only what the steps say. Tap the cards to put them in order (tap a step to take it out again), then press Run and watch. Two of the cards aren’t exact: see what the robot does with them.

potstove: offcups
In the pot
nothing
In the cups
nothing

Robot: waiting for its steps.

Tap the cards below in the order the robot should do them. It needs 8 steps. Then press Run.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Tap a card to add it to the steps:

Hint
Answer

Directions to Nyatapola

Directions are an algorithm too. To give them exactly, you need words that mean the same thing every time. “Forward one block”, “turn left” and “turn right” are good ones.

But be careful: left and right depend on the way you are facing. If you face north, your left is west. If you turn round and face south, your left is east. So an instruction like “turn left” only makes sense if the person following it knows which way they are facing, and an algorithm must keep track of that, one step at a time.

A tall temple with five tiered roofs standing on a high stepped base, with stone figures on each side of the stairs
Figure 3.3 Nyatapola in Taumadhi Square, Bhaktapur: five roofs on five stepped platforms, finished in 1702. About 30 meters tall, it is the tallest temple in Nepal. Photo: Göran Höglund (Kartläsarn), CC BY 2.0

Try it

From the school gate to Nyatapola

This is a small, made-up map of streets near a school. The walker starts at the school gate, facing north (up the map). Give it directions with the three buttons, then press Run. Each forward moves it one block, and houses are in the way.

NyatapolaSchool gateN
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
Step
–
Facing
north

Add steps with the buttons, then press Run. The walker starts at the school gate, facing north.

Hint
Answer

You are walking south. You turn left. Which way are you walking now?

Pick an answer to see why.

Repetition: doing it again

Look at those directions again: “forward, forward, forward”. When a step is done again and again, it is shorter and clearer to say so once: forward 3 times. Doing the same steps again is called repetition.

There are two kinds:

  • Repeat a number of times, when you know how many times before you start: “Fold 40 momos: repeat 40 times: put a spoon of filling on a wrapper, then fold and pinch it shut.”
  • Repeat until something happens, when you don’t know how many times: “Stir until the sugar has dissolved.” “Keep walking forward until you reach Taumadhi Square.” After each time round, you check: has it happened yet? If not, go round again.

Repetition makes algorithms shorter, and easier to change: to fold 60 momos instead of 40, you change one number, instead of writing the steps out twenty more times.

You have to fill water bottles from a tap until the tank is empty. You don’t know how many bottles that will be. Which kind of repetition fits?

Pick an answer to see why.

Choices: if this, then that

Not every step should be done every time. You take an umbrella if it is raining. You add sugar to someone’s chiya if they like it sweet. A step like that, which happens only when something is true, is a choice.

A choice asks a question that has only two answers, yes or no. The question is called the condition. Then:

  • If the answer is yes, do these steps.
  • Otherwise, do those steps (or nothing).

Choices let one algorithm handle different situations. In the spring festival of Bisket Jatra, the great chariot of Bhairab is pulled in Taumadhi Square, beside Nyatapola, and the square is full of people. Your directions could say: “If the chariot is in the square, go round by the next street; otherwise, walk straight across.”

Which of these is a good condition for a choice?

Pick an answer to see why.

Sequence, repetition and choices are the three ways of putting steps together. Computer scientists have shown that these three, with a way to remember things (the next section), are enough to write any algorithm there is, from chiya to the programs on a phone. In Unit 4 you will meet them again, as blocks a computer can run.

Remembering things: variables

Watch the scorer at a cricket match. After every ball, the scorer writes down a few things: how many runs the team has, how many wickets have fallen, the name of the batter facing the next ball, and whether it is the last over yet. The numbers change all through the match, but the scorer always knows where to find them.

An algorithm needs to remember things in the same way. A named place that holds one piece of information, which can change while the algorithm runs, is called a variable. Think of it as a box with a name written on it: you can look at what is inside, and you can take it out and put something new in.

Different variables hold different kinds of information, called data types. The three you will use most are:

Data type What it holds Examples
number a number you may count or calculate with runs = 145, cups = 3, price = 30
text letters, words or any symbols name = “Sita”, district = “Bhaktapur”
yes/no only one of two answers (programmers say true or false) last over = no, raining = yes

The type matters because of what you can do with it. You can add two numbers; you can’t add two names. A yes/no variable is just right for a condition: “if raining is yes, take an umbrella”.

A variable makes an algorithm work for everyone, not only for one person. Here is an algorithm a tea shop could use for any customer’s bill:

  1. Ask the customer’s name. Keep it in name (text).
  2. Ask how many cups. Keep the number in cups (number).
  3. Ask “Milk tea?” Keep the answer in milk (yes/no).
  4. If milk is yes, price = 30. Otherwise, price = 20.
  5. bill = cups × price.
  6. Say: “name, please pay Rs bill.”

The same six lines work for Hari with 2 cups of milk tea and for Maya with 5 cups of black tea. Only what is inside the boxes changes. (The prices here are made up for a pretend shop.) Hari’s name, 2 cups and “yes” are the algorithm’s input, the information it is given to work on; “Hari, please pay Rs 60” is its output. These are the same input and output you met in Unit 1: a computer running this algorithm would take the input from a keyboard or a touchscreen and show the output on a screen.

In the tea shop’s algorithm, which variable is a yes/no variable?

Pick an answer to see why.

In Grade 7 you will make variables in a block program, and build a quiz that keeps your score in one.

Does it work? Checking an algorithm

How do you know an algorithm is right? Not by reading it and feeling sure. You check it, by following it exactly for some inputs, and comparing what it gives with the answer you know is right.

Following an algorithm by hand, step by step, exactly as a computer would, is called tracing it. As you trace, you write down the value of every variable after each step in a table, called a trace table. Each row is one step; each column is one variable. Here is the tea shop’s algorithm traced for Hari, who wants 2 cups of milk tea:

Step name cups milk price bill
1 Hari
2 2
3 yes
4 30
5 60
6 Says: “Hari, please pay Rs 60.”

Milk tea is Rs 30 a cup, so 2 cups should be Rs 60. The algorithm gives Rs 60: it is right, for this input. Trying an algorithm with an input whose right answer you already know is called a test.

Now the shop adds a rule: buy 5 cups or more and get Rs 10 off. Someone adds a line to the algorithm. Is the new line right? Trace it and see.

Try it

Test the tea shop’s bill

Pick a customer and step through the algorithm one line at a time. Before each line, say what it will put in the trace table, then press Next line and check. At the end, compare the algorithm’s answer with the shop’s rule. Test all three customers.

The shop’s rule: milk tea Rs 30 a cup, black tea Rs 20 a cup. Buy 5 cups or more and get Rs 10 off the bill.

  1. 1Ask the customer’s name. Keep it in name.
  2. 2Ask how many cups. Keep the number in cups.
  3. 3Ask “Milk tea?” Keep the answer, yes or no, in milk.
  4. 4If milk is yes, price = 30. Otherwise, price = 20.
  5. 5bill = cups × price
  6. 6If cups is more than 5, bill = bill − 10.
  7. 7Say: “name, please pay Rs bill.”
Customer:

Answers: Hari, 2 cups, milk tea: yes

Linenamecupsmilkpricebill
1
2
3
4
5
6
7
The algorithm says
–
The shop’s rule says
–

Pick a customer and press Next line. Before each line, say what it will put in the table.

Hint
Answer

Notice which test found the bug: Maya’s, with exactly 5 cups, right at the edge of the rule. Hari and Ram both passed, so with only those two tests the bug would have stayed hidden. Choose tests that try every part of an algorithm: each answer of every choice, and the values right at the edges.

An algorithm gives Rs 60 for Hari, and the right answer is Rs 60. What can you say?

Pick an answer to see why.

Bugs and debugging

A mistake in an algorithm is called a bug. (Unit 4 tells the story of where that name came from.) Finding a bug and fixing it is called debugging. Bugs are normal. Everyone who writes algorithms writes bugs; good algorithm writers are good at finding them.

You have already met the most common kinds of bug:

  • a missing step: the stove left on, the chiya never strained;
  • steps in the wrong order: straining before boiling;
  • a step that isn’t exact: “some sugar”, “boil until it’s ready”;
  • a wrong choice: “more than 5” where it should be “5 or more”;
  • a repeat that never ends: “stir until the chiya turns blue”.

To debug an algorithm:

  1. Find a test that fails: an input where the result isn’t what it should be.
  2. Trace it and find the first step where things go wrong. Everything after that may go wrong too, but the bug is usually at, or just before, the first wrong step.
  3. Fix that one thing, and only that.
  4. Test again, with the test that failed and with all the others.

Try it

Fix a friend’s directions

A friend wrote these directions from the school gate to Nyatapola, but they have one wrong step. Run them and watch where the walker first goes wrong. Then tap that step to change it (each tap changes ↑ to ↶ to ↷), and run the directions again.

NyatapolaSchool gateN
  1. 12
Step
–
Facing
north

These are a friend’s directions. Press Run, find the step that goes wrong, and tap it to change it.

Hint
Answer

A friend’s directions make you walk into a wall at step 7. Where is the bug most likely to be?

Pick an answer to see why.

In short

Exercise

What is an algorithm?

Pick an answer to see why.

Which step is done more than once?

Pick an answer to see why.

A variable holds the name of a district, “Lalitpur”. What is its data type?

Pick an answer to see why.

An algorithm says: “Repeat until the bucket is full: pour in one cup of water.” The bucket has a hole in the bottom that lets water out faster than you pour. What happens?

Pick an answer to see why.

Why do we trace an algorithm with a test input whose answer we already know?

Pick an answer to see why.

a.

What is an algorithm? Write three things that every good algorithm has, and give two examples of algorithms from daily life.

Answer
b.

Rewrite these instructions so that a robot could follow them exactly: “Put some rice in a pot with enough water and cook it till it’s done.”

Answer
c.

Explain sequence, repetition and choice, with an everyday example of each.

Answer
d.

You are facing east. You follow these directions: turn left, forward 2 blocks, turn left, forward 1 block, turn left. Which way are you facing at the end? Draw your path.

Hint
Answer
e.

What is the difference between “repeat a number of times” and “repeat until”? Give an example where each is the better choice.

Answer
f.

What is a variable? Copy and complete the table with the data type of each variable (number, text or yes/no).

Variable Value Data type
marks 78
city Pokhara
passed yes
students 32
school Bhaktapur Secondary School
Answer
g.

A school gives a prize to students whose marks are 80 or more. Raju writes this algorithm:

  1. Ask the student’s marks. Keep the number in marks.
  2. If marks is more than 80, say “Prize!”. Otherwise, say “Well done.”

Test it with marks of 92, 80 and 45. Which test finds a bug? Fix the algorithm.

Answer
h.

Make a trace table for the tea shop’s algorithm for Gita, who wants 3 cups of black tea. What does the algorithm say at the end?

  1. Ask the customer’s name. Keep it in name.
  2. Ask how many cups. Keep the number in cups.
  3. Ask “Milk tea?” Keep the answer in milk.
  4. If milk is yes, price = 30. Otherwise, price = 20.
  5. bill = cups × price.
  6. Say: “name, please pay Rs bill.”
Answer
i.

What is debugging? Write the four steps of debugging an algorithm, and say why you should test again with all the old tests after fixing a bug.

Answer
j.

Design an algorithm for a bus conductor that works out one passenger’s fare. A ride costs Rs 30, students pay half, and children under 5 years old ride free. Use variables (with their data types) and choices, and test your algorithm with three passengers of your own.

Hint
Answer