Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 6: Chapter 5 – Planning Programs

Byte by Byte › Book 6: Python, Data and How Computers Work › Chapter 5: Planning Programs

Chapter 5: Planning Programs

You will learn: the three building blocks of every algorithm (sequence, selection and iteration), how to draw a flowchart with the standard symbols, how to write pseudocode, how to dry run an algorithm with a trace table, and how to choose normal, boundary and invalid test data.

🌟 The Adventure

Octavia's question kept Memoon awake that night. Can you write instructions?

In the morning Octavia showed her what she meant. Every hour, day and night, the Riverbend tide gates had to be set by hand. Octavia swam to the gate tablet, read the water level from a glowing gauge, thought about it, and set the dial. If the water was high, the gate closed to stop flooding. If it was very low, the gate opened fully so the river would not dry up. Otherwise it stayed half open.

"I have done this twenty-four times a day for two hundred years," said Octavia. "If you can write those instructions so the Engine follows them by itself, I can rest at last."

Memoon was ready to start immediately. She grabbed a blank tablet and began carving. Kachui, who had come down to visit in his own small breathing bubble, put out a flipper and stopped her.

"Slow, steady, in order," he said. "You are going to carve instructions onto stone for a machine that will follow them exactly, every hour, for years. What happens if they are wrong?"

Memoon looked at the tablet. Mistakes in stone are hard to rub out. "I need a plan first," she said.

💡 Learn With Memoon

Algorithms, again. You already know that an algorithm is a precise, step-by-step set of instructions for solving a problem. In Book 5 you learned to decompose a problem before writing algorithms. This chapter gives you two professional tools for writing algorithms clearly before you turn them into code: flowcharts and pseudocode.

The three building blocks. Every algorithm, however big, is built from just three structures. Computer scientists proved that these three are enough to write any program at all.

Building

What it meansEveryday example

block

SequenceSteps carried out one after another, in orderWash, rinse, dry
SelectionChoosing which steps to do, based on a conditionIf it is raining, then take an umbrella, else wear a cap
IterationRepeating steps, either a set number of times or until a condition changesStir 20 times; keep walking until you reach school

You met all three in Scratch: a stack of blocks (sequence), if then else (selection), and repeat, forever and repeat until (iteration). They are called programming constructs, and you will meet them again in Python in the next three chapters.

Flowcharts. A flowchart is a diagram that shows an algorithm as shapes joined by arrows. Each shape means something different. Everyone uses the same shapes, so anyone in the world can read your flowchart.

SymbolShapeUsed forExample
TerminatorOval (rounded rectangle)Start and StopStart
Input/ OutputParallelogram (slanted rectangle)Getting data in or showing data outInput waterLevel; Output "Gate closed"
ProcessRectangleA calculation or actiontotal = a + b
DecisionDiamondA yes/no question; two arrows leave it, labelled Yes and NoIs waterLevel > 15?
Flow lineArrowShows the order of steps→
ConnectorSmall circleJoins parts of a flowchart that do not fit on one page(A)

Rules for a good flowchart: exactly one Start and at least one Stop; arrows show direction and never cross if you can avoid it; every decision has exactly two labelled exits; and every path eventually reaches Stop (unless the program is meant to run forever).

A sequence flowchart. Find the average of three test marks:

( Start )
    |
    v
/ Input mark1, mark2, mark3 /
    |
    v
[ total = mark1 + mark2 + mark3 ]
    |
    v
[ average = total / 3 ]
    |
    v
/ Output average /
    |
    v
( Stop )

A selection flowchart. Is a number even or odd? A number is even if dividing it by 2 leaves a remainder of 0.

( Start )
    |
    v
/ Input number /
    |
    v
< Is the remainder of number / 2 equal to 0? >
    |                     |
   Yes                    No
    |                     |
    v                     v
/ Output "Even" /    / Output "Odd" /
    |                     |
    +----------+----------+
               |
               v
           ( Stop )

An iteration flowchart. Add up the numbers from 1 to 10. A loop is drawn as an arrow that goes back up to an earlier step.

( Start )
    |
    v
[ total = 0, count = 1 ]
    |
    v
< Is count <= 10? > --No--> / Output total / --> ( Stop )
    |
   Yes
    |
    v
[ total = total + count ]
    |
    v
[ count = count + 1 ]
    |
    +----> (back up to the question)

Notice the two special variables here. total is an accumulator: it starts at 0 and has something added each time round the loop. count is a counter: it goes up by 1 each time and controls when the loop stops. You will use these two patterns constantly.

Pseudocode. Flowcharts are easy to see, but big ones become huge. Pseudocode writes an algorithm in short, structured English-like lines. Pseudo means "pretend": it looks like code, but no computer runs it. It lets you think about the logic without worrying about the exact rules of a programming language. There is no single official pseudocode, but most people use words like these:

Pseudocode wordMeaning
INPUTGet a value from the user
OUTPUTShow a value
= or ←Store a value in a variable
IF ... THEN ... ELSE ... ENDIFSelection
FOR count = 1 TO 10 ... NEXT countRepeat a fixed number of times
WHILE condition ... ENDWHILERepeat while a condition is true

Indent the lines inside an IF or a loop, just like the blocks inside a C-block in Scratch. Here are the three flowcharts above as pseudocode:

INPUT mark1, mark2, mark3
total = mark1 + mark2 + mark3
average = total / 3
OUTPUT average
INPUT number
IF number MOD 2 = 0 THEN
    OUTPUT "Even"
ELSE
    OUTPUT "Odd"
ENDIF
total = 0
FOR count = 1 TO 10
    total = total + count
NEXT count
OUTPUT total

MOD means "the remainder after dividing". 17 MOD 5 = 2, because 17 ÷ 5 = 3 remainder 2. You will meet it again in Python.

Dry running. Before a program is typed, programmers dry run the algorithm: they pretend to be the computer, follow it step by step with real values, and record every variable in a trace table, as you did in Book 5. Dry running the sum algorithm:

countcount <= 10?total
1Yes1
2Yes3
3Yes6
.........
10Yes55
11No55 (output)

Dry running catches logic errors: mistakes where the steps run without crashing but give the wrong answer.

Choosing test data. One test is never enough. Good testers choose three kinds of test data:

Example for "a test mark from

KindMeaning

0 to 100"

NormalOrdinary, sensible values45, 72
BoundaryValues at the very edge of what is allowed, and just past it0, 100, and also −1 and 101
Invalid (erroneous)Values that should be rejected−50, 250, "seventy"

Boundary values are where most bugs hide, because programmers mix up "greater than" (>) and "greater than or equal to" (>=). If the rule says "a mark of 33 or more is a pass", then 33 must pass and 32 must fail. Test both.

💡 Memoon’s tip: For every decision diamond in your flowchart, test at least one value that goes down the Yes path, one that goes down the No path, and the boundary value exactly on the line.

Illustration from Byte by Byte Book 6: Chapter 5 – Planning Programs

✍️ Try It Yourself

Activity 1: Spot the building blocks. For each, write sequence, selection or iteration (some have more than one): (a) brushing your teeth for two minutes; (b) deciding what to wear based on the weather; (c) a recipe for chai; (d) a traffic light; (e) climbing stairs until you reach the top floor.

Activity 2: Draw flowcharts. Draw a flowchart, using the correct symbols, for each of these:

  1. Input the length and breadth of a rectangle and output its area and perimeter.
  2. Input a person's age. If it is 18 or more, output "Can vote", otherwise output "Cannot vote yet".
  3. Output the 5 times table from 5 × 1 to 5 × 10.

You can draw them on paper, or in Word or PowerPoint using Insert → Shapes (the Flowchart group has every symbol), joining them with arrow connectors.

Activity 3: Write pseudocode. Write each of your three flowcharts from Activity 2 as pseudocode.

Activity 4: Dry run and test. Here is an algorithm for a school's grading system:

INPUT mark
IF mark > 90 THEN
    OUTPUT "A"
ELSE IF mark > 75 THEN
    OUTPUT "B"
ELSE IF mark > 33 THEN
    OUTPUT "C"
ELSE
    OUTPUT "Needs improvement"
ENDIF

The school's rule is: 90 and above is A, 75 and above is B, 33 and above is C. Dry run it with the test data 95, 90, 80, 75, 50, 33, 20 and −5. Which results are wrong? What kind of test data found the bugs? Rewrite the algorithm so it follows the rule. Then add a check that rejects marks below 0 or above 100.

Unplugged: Human robot. Write pseudocode for a partner to walk from one side of a room to a chair and sit down, using only these commands: STEP FORWARD, TURN LEFT, TURN RIGHT, SIT, and a loop such as REPEAT 4 TIMES. Your partner must follow it exactly, even if it leads them into a wall. Fix your algorithm until it works first time.

🎉 Memoon Solves It

Memoon put the stone tablet aside and took a slate and chalk. First she asked Octavia exactly how she decided each hour. Then she drew it as a flowchart: Start, input the water level, a decision diamond, three outcomes, Stop. Then she wrote it as pseudocode:

REPEAT every hour
    INPUT waterLevel
    IF waterLevel > 15 THEN
        set gate to CLOSED
    ELSE IF waterLevel < 5 THEN
        set gate to FULLY OPEN
    ELSE
        set gate to HALF OPEN
    ENDIF

"Now dry run it," said Kachui.

Memoon tried normal values first: 20 (closed), 2 (fully open), 10 (half open). All correct. Then she checked boundary values. "What should happen at exactly 15?"

Octavia thought. "At 15 the river starts to flood the frogs' lily pads. The gate must close at 15."

Memoon looked at her pseudocode. waterLevel > 15 meant greater than 15. At exactly 15 the gate would stay half open, and the frogs would wake up underwater. She changed it to waterLevel >= 15 . Then she checked 5, then 4, then a broken gauge reading of −3, and added a line: if the reading is below 0, sound the alarm for the Keeper.

"Every path tested," said Kachui, and he looked as pleased as a turtle can look.

"Now," said Octavia, "you must say it to the Engine in a language it understands." She led them to a smooth black stone set into the wall of the core. It had a blinking cursor. Beside it, carved in the Old Makers' letters, was a single word. Memoon read it, and laughed out loud, because it was the word on her backpack sticker.

❓ Check Your Knowledge

  1. Name the three building blocks of algorithms and give an example of each.
  2. Draw and name the flowchart symbols for: start/stop, input/output, process, decision.
  3. Why does a decision symbol have two arrows leaving it?
  4. What is pseudocode, and why do programmers use it instead of writing code straight away?
  5. What is 23 MOD 4? What is 30 MOD 5?
  6. What is the difference between an accumulator and a counter?
  7. What is a dry run? What kind of error does it help to find?
  8. A program accepts ages from 5 to 15. Give two normal, four boundary and two invalid test values.
  9. Write pseudocode that inputs two numbers and outputs the larger one.
  10. True or false: a computer can run pseudocode directly. Explain.
  11. Challenge: Draw a flowchart and write pseudocode for a guessing game: the secret number is 7; the player keeps guessing until they get it right; after each wrong guess the program says "Too high" or "Too low"; at the end it says how many guesses they took.

📚 Word Bank

  • Sequence: steps carried out in order, one after another.
  • Selection: choosing which steps to carry out based on a condition.
  • Iteration: repeating steps; another word for looping.
  • Programming constructs: the three building blocks of programs: sequence, selection and iteration.
  • Flowchart: a diagram of an algorithm using standard shapes joined by arrows.
  • Terminator: the oval flowchart symbol for Start and Stop.
  • Decision symbol: the diamond flowchart symbol for a yes/no question.
  • Pseudocode: an algorithm written in structured, English-like lines that is not a real programming language.
  • MOD: the remainder after dividing one whole number by another.
  • Accumulator: a variable that builds up a total, usually starting at 0.
  • Counter: a variable that counts how many times something has happened.
  • Dry run: following an algorithm by hand, step by step, to check it works.
  • Logic error: a mistake that makes a program give the wrong result without crashing.
  • Test data: values chosen to check that a program works correctly.
  • Boundary data: test values at the edges of what is allowed, and just outside them.

Keep learning with Byte by Byte

Explore Book 6: Python, Data and How Computers Work. Find the ebook, purchase details and teaching slides on MemuniCity.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...