304 123 28MB
English Pages [35] Year 2015
THIS PAGE LEFT BLANK INTENTIONALLY
Firs Fi F rst pu publ blis ishe hed d in 2 201 015 5 by Way ayla land nd Copy Co C pyri righ ghtt © Wa W yl y an and d 20 2015 15 Waylan Wayl and d 338 33 8 Eu Eust ston on R Roa oad d Lo ond ndon on NW1 3BH Waylan Wayl and d Au Aust stra ralilia a Leve Le el 17 7/2 /207 07 K Ken entt St Stre reet et Sydn Sy dney ey,, NS NSW W 20 2000 00 A l riigh Al ghts ts res eser erve ved d Commis Comm issi sion onin ing g Ed Edit itor or: De Debb bbie ie e Foy y Proj Pr ojec ectt Ed Edit itor or:: Ca Caro roli line ne W Wes est (B Blu lue e Dr Drag agon onfl fly y Lt Ltd. d..) Desi De esi ssign gner g er:: Ma e Mark rk kL Lat a te ter r (B (Blu lue e Dr rag agon onfl fly y Lt Ltd. d) A ca cata talo logu gue e re eco cord rd for thi hiss ti titl tle e is a ava aililab a able le frrom the Bri r ti t sh L Lib ibra rary ry. ISBN: 97 ISBN 978 8 0 75 7502 02 9 921 216 60 eBoo eB ook k IS ISBN BN:: 97 978 8 0 75 7502 02 921 9217 77 Dewe De wey y nu numb mber er: 00 005. 5 11-dc dc23 23 Prin Pr inte ted d in C Chi hina na W yl Wa y an and, d, p par artt of Hac ache hett tte e Ch Chilildr d en en’s Gr Grou oup p and an d pu publ blis ishe hed d by Hod odde derr an and d St Stou ough gh hto ton n Li Limi m te ted d www. ww w.ha hach chet ette e.c .co. o uk All im A imag ages es cou ourt rtes esy y of Shu hutt tter erst stoc ock k ex exce ce ept pt:: p5 (to top p le left)) Da Dailily y Hera rald ld A Arc rchi hive ve/N /Nat atio iona nall Medi Me dia a Mu Muse seum um/S /Sci c en ence ce & Soc ocie iety ty P Pic ictu turrre Lib ibra rary ry; p5 ((bo bott ttom om rrig ig ght ht)) Sc Scie ienc nce e Mu Muse eum um// Scie S Sc ienc ie nce e & So Soci ciet iet ety ty Piict ctur ure e Li L br brar ary; y; p p12 12 2 ((bo bott bottom ttom om lef eft) t)) W Wik ikimed ikim edia ia Com ommo mons ns/V /Val a ia iant n Tech Te chno nolo logy gy Ltd td.;; p p13 3 (to top p le left ft)) Va Valilan antt Te ech chno nolo logy gy Ltd td.;; p p14 14–1 –15 5 Scra ratc tch h (S (Scr crat a ch is a proj pr ojec ectt of tthe he Lif ifel elon ong g Ki K nd nder erga gart rten en G Gro ro oup at th the e MI MIT T Me Medi dia a La Lab b); p1 p19 9 (t (top op) Liigh ghtb tbot ot Inc nc.;. p28 p2 8 (b (bot otto tom m ri righ ght)) IISt Stoc ockp kpho hoto o/E Ed St S oc ock k. k. While Whil e ev ever ery y at atte temp mptt ha has be been en mad ade e to cle lear ar c cop opyr yrig ight ht, sh shou ould d there be an any y in nad adve vertten entt omisssi om sion on thi hiss wi willll b be e re rect ctif i ie ied d in i fut u ur ure e edittio ions ns.
Discla Disc laim imer e : Th The e we webs bsit ite e ad addr dres esse sess (U URL RLs) s) inc nclu lude ded d in n thi hiss bo book ok wer ere va valilid d at a the time ti me of go goin ing g to pre ress ss.. Ho Howe weve ver, r, b bec ec cau a se of th the e na natu ture re of th he In nte tern rnet et,, it i is po p ss ssib ible e that th at som ome e ad addr dres esse sess ma may y ha have ve c cha hang ng ged ed,, or o sit i es e may h hav ave e chan change ged d orr clo ose s d do down wn s nc si nce pu publ blic icat atio on. n W Whi hile e the aut utho horr an nd pu publ blis ishe herr re regr gret et a any ny y inc ncon onve veni nien ence c thi ce h s ma may y caus ca use e th the e re read ader ers, s, n no o re resp spon onsi sibi bilility ty for any suc uch h ch chan ange gess ca an be acc cep epte ted d by eit ithe herr the th e au auth thor or o orr th the e pu publ blis ishe her. r Note tto Note o re read ader er: Wo Word rdss hi high ghliligh ghte ted d in b bol old d ap appe pear ar iin n th the e Glos Glo sa sary y on pa page ge 30. Answ An swer erss to act ctiv ivit itie iess ar are e on p pag age e 31 31.
Contents 4 6
Cod ding your World Alg gorithms in Action
8 10 12 14 16 18 20 22 24 26 28
One es and Zeros Min nd your Language Lan nguages for Learning Scra atch! Acc curate Algorithms Gett in Step Dec cisions, Decisions Go with the Flow Goiing Loopy A Bu ug’s Life Cod ding Careers
30 31 32
Glo ossary Furt Further ther Resources Index
g n i d Co
your
d l r Wo
Computters are everywhere. Whenev ver you heat food in a micrrowave, watch an animated movie or play with a smartp phone, you are using compute er technology. But all this tech hnology won’t work unless y you ou tell it what to do do.
IT S IT’S YOUR TURN
4
HELP! H
? Helping ha ands Althou ugh computters may seem m very y powerrful, th hey ne eed people to o lend da hand. Computers can’t act on n their own and allways need a seriess of in nsttruc ctions to tell them wh hat to o do. These instructions are calle ed program ms. Writing g programs is called coding and is c an carried ou ut by peop ple known as cod ders, or programmers. d With a program installed, comp puterss’ biig bra ains ca a an ru un sup per-sm mart code e to do a amazing things. For exam mple, in 1997 7, IBM 7 M’s Deep Blue comp puter running g a chess-playing progra am be eat the Wo orld Champ o pion chesss pla ayer, Garry K Kasparov. Result!
nk there I thin is a world be may market for uters. ve comp fiiv
TRUE STORY
in use at the r te pu m co 10 14 M IB in 1969. ny pa om C or ot M d For
Computers Galore 7KRPDV:DW WVRQ ZKRZD DVRQFHFKD DLU UP PD DQ Q R RI I , %0 PDG GHW WKLVSUHGLF FWLRQLQ ZKHQ QFRPSXWHUV VZHUHºUVW LQYHQWHG+RZZ ZURQJKHZD DV 7KHU UHDUHQRZRYHU PLOO OLRQFRPSXW WHUVLQWKH H ZRUO OG GDQG G PLOOL LRQVPRUH smar rtphonesDQ QGWDEOHWV
ER COMPUT
Hero!
7KHZRUOG±Vº ºUVW º UVW WFRPSXW F WH HU SURJUDPPHUZ SURJUDPPHUZDVD 9LF FWRULDQZ ZRPDQ FDOOHG$GD&RXQW WHVVRI/RY YH HODFH +HUIULHQG&KDUOHV V%DEEDJHW WU ULHGWR EXLOGWKHºUVWFRP PSXW WHUV,Q Q $GDZURWHDVHULHV VRI ILQVWUX XF FWLRQV WRGRVRPHFRPSO OLFDWHGPDW WK KVRQ %DEEDJH±VPDFKLQ QHVLIWKH\ \ZHUH FRPSOHWHG$GDKDGZULWW L WH HQ WKHºUVWFRPSXWHUSURJUD DP P
Ada, Countess of Lovelace 5
s m h t i r Algo n
o i t c in A
A comp All puter programs rely on algorrithms. These are sets of step-b by-step instructions to perform m tasks or solve problem ms. Coders use algorithms to help them pla an out their programs.
Ever E veryday ryday y algoritthms You use algorithms all the time, pro obably without even knowing it. Recipes fo or making different foods and drinks a are types of algorithm. For example, w when you make a glass of squash, you kn now to open the squash bottle, pour the ssquash into a glass and then add water. Th he algorithm for this task might be written n as: a as
ttle top 1. Remove squash bo s 2. Pour squash into glas 3. Turn on tap ter 4. Fill glass up with wa off tap 5. When glass full, turn 6. Drink!
Sh hare the sweets! Yo Y ou also l use algorithms l ith tto solve l prroblems. Say you’ve been given ab big bag of sweets, but have to share them equally. You need to fin nd a way to share the sweets out. Herre are two algorithms for doing this:
haring: Sweet Sh 1 Algorit m e e in a circle n o ry e v e e g 1. Arran weet to ne sw 2. Hand out o rn
u in tu each person weet, one has a sw ry e v e n e h W 3. 2 one lf e rs u o y e iv i g s 2–3 until all p e st t a e p e 4. R re gone the sweets a
Sweet Shari Alg gorithm 2ng: 1. Count all t he sweets 2. Count how m
any people th here are 3. Div vid de number o f sw weets by number o f people e 4. Giv ve each pers on th he same numb er of sweets as th he answer
l yer: ickla Robot Bhrm 1 Algorit ne up s and pick o k c ri b to o G 1. all 2. Return to w on wall 3. Place brick o ps 1–3 until n 4. Repeat ste
Diffferent method ds,, same target Just like the sweet-sharing algorithms, there are many computer algorithms that can do the same job. Programme ers spend lots of time thinking through the eir algorithms, trying to come up with the e fastest or most efficient way to perform m a task.
bricks left
Here are two different algorithms to o tell a robot how to build a brick wa all. all. Which algorithm do you think will get the wall built most quickly?
Robot icklayer: AlgoritBhrm 2 1. Go to whe e
lbarrow and push to bricks 2. Filillll wheelb arrow with all the bricks 3. Push whee llb barrrow to t wall 4. Place brick on wall 5. Repeat ste p 4 until no bricks left
Write Instr t uctions
for a Recip e
Can you an d a friend ea ch write an a making a m lgorithm for eal that you b oth like? Use make the re lots of steps cipe really c to o lear. Compa re your result s:
My
Recipes
Did your frie nd come up with someth you didn’t th ing that ink of? Can you thin k of another recipe meth would give y od that ou the same result?
7
All computers are packe ed with electrical circuits. These carry tiny pulses of elec ctricity that act like a code, send ding data d ata as streams of just tw wo numbers – 1 and 0. n
and s e n O ros Ze Number systems You use the decimal, or base 10, number system every day when you are counting or doing sums. The decimal system contains 10 different digits (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9). When you want to count higher, you add an extra column on the left and continue counting – 10, 11, 12.
DECIMAL
0
1
2
BINARY
0
1
10
3
4
5
6
7
Binary iss another number system. It uses only two o numbers – 1 and 0. When you want to go higher than 1 in a column, you put a 1 in the next column on the left and then sta art counting from 0 again in the first colu umn on the right. Below is a table showing g the binary numbers up to 15.
8
9
10
11
12
13
14
15
11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
STRETCH F YOURSEL al to Binary en see if you can work out im c e D e g 9, th Chan binary? od on page
17
16
he meth ht) are in Look at th numbers (rig l a im c e d e re what these th
.
s an example a 5 1 r e b m u done n imal 1111 is dec r e b m u n So, binary . 5 1 = 1 number 15 16 8 4 2 ach can use e u o y r e b m 1 Reme 1 1 1 ly once! number on
Answers o
8
n page 31
21
Have a look at thes e examples:
C l Column calculation l l ti ns Binary can be turned into decimal numbers, and vice versa. You just need to remember that each column of a binary numbe er is worth twice as much as the previous column. So, the first five columns of binary numbers equa al 1, 2, 4, 8 and 16 if they are written n as decimal numbers. The first column is always on the right, and you add new ones on the left. If you write a binary number underneath the columns of decimal values, you can work out the value of the binary number. All you need to do is add together the decimal numbers that have a 1 beneath them.
Convert binary y numbe er Columns Decimal Binary
101 to a decim c al numb be err::
16 8 4 2 1 1 0 1 =4+1=5
HELPFUL TIP:: The binary numberrs show which decima al values to add together!
Add together the de d cim i all numb bers that h have a 1 beneath them. So, binary number 1 0 1 equals decimal numbe r5 Convert binary numbe Columns Decimal Binary
r 10010 to a decimal nu
mber:
16 8 4 2 1 1 0 0 1 0 = 16 + 2 = 18
Add together the decim al numbers tth ha att have a 1 beneath them. So, binary number 1 0 0 1 0 equals decimal number 18
STRETCH YOURSELF Bec Be co om me e a Binary Spy!
Answers on page 31
Make a secret number system on your left hand by using washable ink to "#"$ % " " 16 6 on your thumb. You now have a binary code Y & ' * sticking up equals a binary 1. Ca n you tell a friend (without speaking) what number you are thinking of just by using your hand?
Here are some examp ple les: + -/ + / ; < = ;
-> @ @
-$'%A$A#* B E you need to hold up to make 6, 10, 13 and 20?
your d Min
e g a u g n La
Early computers were programmed d using i long l series of binary numbers. These took ages to key in n and also to check if a mistake was made! The in nvention of the compiler alllowed programming lan nguages to be created, which wh h made coding easier.
Compute ter talk t lk A programming language iss made up of commands or instructions that are like building blocks. Coders arrange these blocks in diffe erent ways to build code and prog grams. The language takes care of tiny but important details such as ho ow to add up two numbers or where to o store data. Some well-known com mputer languages are described he ere.
Hello Hello Hello Hello
Mum Mum Mum Mum
BASIC Your parents probably used this when computers first entered homes in n the 1970s and 1980s. BASIC used Eng glish language commands, with each h command placed on a numberred line. For example, the program below w will display rows of ‘Hello Mum’ messsages on a computer screen:
10 Print ‘He llo Mum’ Print
means displa y on the comput er’s screen.
20 GOTO 10
GOTO is a BA SIC command tto o jump to a differen t line number.
JAVA This is ussed to write e small games and programs for smartphones, table ets an nd computers. Java is also used d for mak king animate ed cartoons ns on web b pag ges.
C+++
SQ SQL QL Thiss lang g ua age was developed by IBM M and d is used to create databases. A dattaba ase is an applica ation that stores larg ge amounts of information in an org ganised way, so that you can find it again easily.
UTER P M O C o!
Her
This advanced d and very powerful language has bee en used to write many famous com mputer program ms. These incllude Microsoft Office and d bro owser prog gramss such as Google Chrome and Apple Saffari that arre used forr viewing web pages. pages
KH pperEXLOWW H o H e c a r G ,Q OOHGWK rSURJUDPFD ºUVWcompile UDFHEHOLHYHGWKDW * $V\VWHP XOGEHSURJUDPPHG R K LVK FRPSXWHUVV WWHQLQ(QJO LQJ L U Z V G Q D P P R XVLQJF URJUDPP UGWRPDNHS WKLV D K G H N U R Z G DQ DWFRXOGGR ODQJXDJHVWK
11
s e g a u Lang
g n i n r a e
for
L
Every programming language has its own commands and ways of doing things. Some languages aren’t that diffcult and are designed for people to learn coding… including you!
STRETCH YOURSELF S aki Spea king LOGO!! Control the Turtle
The LOGO language was inve ented d by an American scientist called Seymour Papert in 1967. It let children program a little robot called a turtle to mov ve aro ound the floor. Typing a command such as Forward 20 steps would make th he robot move forward 20 steps, whilst typiing Left 180 degrees wou uld make it turn round 180 degrees (half a circle)). Some turtle robotss carried a pen so you could pro ogram them to draw on paper.
The LOGO language use s simple commands to make the turtle draw different shapes. Try using LOGO to work ou t the answers to these questions: Which one of the follow W ing shapes w uld this LOGO progra wo m draw? Forward 100 steps Left 120 degrees Forward 100 steps Left 120 degrees Forward 100 steps
b
c
d
TThis LOGO program makes the turtle draw a +
to make it draw a square instea d?
Answers on page 31
eps 120 ste Forward e r deg es Right 90 s 100 step Forward s e e r deg Right 90 s 120 step d r Forwa s e e r deg Right 90 s 100 step d r a Forw
12
a
Othe er fun langaua langauages ages Other programming languages include e Kodu, Python and Scratch (see pages 14–15). Kodu uses pictures as programm ming commands to make fun cartoons and simple games on some personal comp puters and the Xbox 360 games console. Pyth hon is a text-based programming language e that uses familiar-sounding words. Altho ough Python can take longer to learn, you can use it to write many types of program.
Inffa fant K–1 Roamer
The robotts are comin ng! Many schools have mobile e robo ots such as Roamers or Bee-Bo ots tha at you can program to move e. You press buttons on top of the e robo ot to enter a series of command ds. The ese commands form a simple progra am. When you press ‘Run’ or ‘G Go’, the e robot carries out the comm mandss you entered in their exact orde er.
You can program th his fun Lego Mindstorm ms robot to move arou und..
STRETCH YOURSELF ch Challenge Robot Rocket Laun
I e robot has to make eight movements th rocket. Can you to follow a path to his g nine commands work out the remainin h his rocket? he must follow to reac
age 31 Answers on pa
d 1 space ard war forrw 1. Move fo 1 htt igh ig r he t to n urn 2 Tur 2. 1 space d ard ar w rw for fo e ov ov Mo 3. M t lef th the to 4. Turn
d 1 space ard war forrw 5. Move fo 5 eft ef l n to the t urn 6 Tur 6. d 2 spaces ard war forrw 7. Move fo e lef 8. Turn to the t 8
13
Scratch is one of the most popular learning languages used in schools. Scratch lets you u mix sounds and picturess to create fun games and d animated cartoons.
! h c t a cr
S
Sprite e right Scratch programs are called scripts. They feature pictures of little c characters called sprites. You can progra am a sprite to move, change appearanc ce, say little messages in speech bub bbles or do o something when they touch tthings or come across other sprites.
Palette point in direction n 90 point towards p
Stage
go to x: 0 go to
wait repeat p peat
glide e 1
secs to x: 0 y: 0 forever
chang ge e x by 110 0 set x to
i t Scripts are rea
0
change y by 110 0 set y to
The first sprite you’ll see in thiss language e is a cat called Scratch. Otherr sprites include dinosaurs, bears and ghosts, or you can draw your own.
y:: 0
mouse-pointer ointer
0
if on edge, bounce
move mov
110 0
play drum
set roation style style
x posaition n
step st ps 4
for
0 0.2 beat beats ts
left-ri left eft right
Next, say something g.
y position direction
Scratch sc creen Sc cratch the Cat
A Scratch S screen has three main n parts: the e palette, scripts area and stage. The pa alette stores all the Scratch insttructions (ca alled blocks) that you can use e. You ca an pick and move the blocks from the e palette to the scripts area, w where yo ou snap the blocks together to build a script s to create your program. Your Sc cratch program is then displaye ed on the e stage.
14
TRUE STORY
Sc cratch t h bllocks k M Many types t off block bl k are used d in Scratch. S These are all colour-coded. You sn nap together the different blocks to build b ild a program. Below are the ones you’ll probably p robably use th the most:
10
MOVE
A Big Hit 7 KRX YLVLWWKH VDQGVRISHRSOH R ZHEVLWH¬ ҬLFLDO6FUDWFK VFUDWFKPL HYHU\GD\ WHGX¬ % ºYHPLOOLR \-XQHRYHU QSUR FUHDWHGRQ MHFWVKDGEHHQ WKHZHEVL WH
STEPS
Motion Motion Blo ocks like these make the sprites move ac cross the stage and change diirection.
PLAY
SOUND
STRETCH YOURSELF
MEOW
Expl E p ore Scratch!
Sounds These blocks play sounds. You ca an pick a sound, such as a drum or cat’s m meow, or record and add your own. WAIT
3
http://tinyurl.com/watchdjcat
SECS
Ev vents The ese blocks control when parts of the scrript run, such as repeating som me of the scrript or waiting a few seconds ffirst.
SAY
HELLO
FOR
2
Look at this Scratch program of a DJ cat mixing sounds . You can add to these sounds by pr essing some of the keys on your keyb oard. Just type this address into a w eb browser:
SECS
Looks These bllocks show differe ent things such as a spe eech ch bubble or a change chang of costume e for your sprite on the screen.
Check out other peop le’s Scratch programs by typing this address into a web browser: http://tinyurl.com/starter-proj
ects
Click on each screen to load the program and then on the K N what blocks were used to make each program by clicking on See Inside.
Computers need more precise instructions than you. A computer will only do what it is told and so needs to be instructed very carefully. This can ttake lots and lots of steps.
e t a r u c c A s m h t i r o g l A
Here e e iss a another o e example e a p e of o an a a algorithm, go , this time for brushing gy your teeth:
Be B e precis pr recise se People have to be very acc curate when creating algorithms. M Missing issing out important steps or getting one wrong can mean the program doe esn’t work. For example, an algorithm fo or a robot to walk forwards needs to contain steps that tell the robot to sttop if it reaches a cliff edge. Othe Otherw e wise, it will continue ue walkin walking ng and fall offf!
1. Turn on ta ap 2. Squeeze toothpaste tube 3. Use brush to clean teeth 4. Put cap on toothpaste The algorithm m does doesn’t sn t say what wh hat sort o of brush to use, to take e the cap off the ttube before squeezing it,, or to turn off the tap. Oops! What ste eps could you add d to make m ake this algoritthm thm w work bett better?
TRUE STORY DQHZ $1 Miillion Lost ,Q O \ RLO REX\ WR USURJUDPW HU WH XW SX S FRPS V ZD \ DQ S PS UDQ$PHULFDQFR IRU P KP LW RU DOJ FKHGRQ%XWWKH VZLWFK ZPDQ\ QROLPLWRQKRZ G DG KD H¬DQG DN G UVLWFRXOGP RUGH HUWV V([SH GV QG DQ VD V XV RX KR WK HW GH DG PD P LWP VRL RY RVW YHU L NWKHFRPSDQ\O WKDQ WKLQ Q V PLOOLRQLQOHV ºYHVHFRQGV
16
STRETCH YOURSELF A-Maze-ing Algorit hms
Build a maze with bo xes and cushions. == movements you wou ld have to make to travel through the maze without bumping into any of the obstacles. Blindfold a friend or parent and read out the commands in order and one at a time. They have to do exactly what you command.
Now, ask yourself thes
e questions:
d d you have to mak di e any changes? D you need to add Do extra steps and commands to your al c gorithm? How many runs of yo H ur algorithm did y u need before it w yo orked perfectly?
An a ans nswer swer f everything for thi Coders have to think through every possibility in their algorithm m. This includes what they would lik ke to happen, but also all the things that could happen. For example e, a quiz game algorithm may only y need ‘yes’ or ‘no’ answers. But if tthe user types in a different word, the e algorithm would have to say tha at it only accepts ‘yes’ or ‘no’ answerrs and ask the question again.
Breaking g things dow wn Many tasks are made up of much smaller on nes. A good algorithm breaks a task k do own into as small a series of steps ass po ossible. This is called decomposing. Fo or example, you could break down an n algorithm for making breakfast into o sm maller tasks such as make toast, pour glass of juice and boil egg. Each of th hese ca an be broken down into smaller step ps.
17
Get
The steps in an algorithm have to be not only precise, bu ut also in the right order. If you get the steps in the wrong order, then the algorithm is unlikely to o work properly.
in
p e t S
Jumping around Keeping track of the steps in n an algorithm can become more e complicated if it is designed to jump back to an earlier point. This simple algorithm (right) keeps track k of a footballer taking shots at a g goal. But the score isn’t going up each time he scores. Can you work outt what is wrong with the algorithm?
1. @ -/ 2. Player sho oots 3. 4. If a goal wasn’t scored, go to liine 2 5. If a goal was scored, add d one to Score and g go to o line 1
This algorithm almost works, work ks butt every time line 5 adds one to the score, it jumps back to line 1, which sets the score to zero again! The solution is simple: line 5 should end with ‘go to line 2’.
STRETCH YOURSELF ctions? You Fix the Instru Can Y ctions for H re are some instru He ey’re all having a bath, but th put them Can you p mbled up. C jum d r? t e right orde in th
g plug 1. Put in bath p 2. Get dressed ater 3. Fill bath with w 3 4. Get into the bath 4 5 Wash 5.
Answers on page 31
18
g plug 6. Take out bath p 6 b th he ba Get out of th 7. G 7 8. Get undressed 8
STRETCH YOURSELF Make Lightbot Move!
If you have Internet access, wh y not visit and play with Lightbot? This fun game lets you choose from a series of simple commands to build a pro gram that will make the little robot mo ve. The tasks start off easy but get harder, so you really have to think throu gh what commands to use and in what order.
You ou can visit Lightbot by typ ping this address into a we eb browser:
http://tinyurl.com/light-robo
t-game
Subroutin nes Some parts of an algorithm m, suc ch as displaying a messa age on n screen, may be needed ag gain and again. But this me eans that the algorithm can ge et very long. So, clever co oders wrrite these parts as sections ca alled subroutines. Co oders only have to write a sub broutine once and then n dirrect the program to jump to it when it needs to use it. This ma akes writing complicated pro ograms easier and faste er.
HIGH SCORE
768.987.000
In this game, when a pla ayer shoots a spider, th he program goes to a subroutine to show an explosion and then another th subroutine b ti to t add points to the score displayed on screen.
, s n o i Decisions s i c e D
Most computer programs have to make decisions along the way. Although some decisions are simple, more complicated ones need to be broken down into lots of small decisions.
If… f Th Then n M Many programs ask k a computer t to to make decisions based on the information n that they receive using an IF statementt. This states that IF something is true, THEN the program will respond and do some ething. l i In computer programs, decisions a are made all the time. For example, in the
car-racing game below, the game’s code has to make lots of different decisions. Then, when the program for the race decides that the game should end, it runs a particular piece of code to give the player a final score and printss ‘Game Over’ on the computer screen n. This is called code selection.
tor, ess the accelera esssse pre r e ye la p e th If e car up then speed th
If the car bumps int i o another car, then slow the the car down and mak ke crash hin ng sound
If the carr ru uns out of fuel, then n gam me over
If the player presses the brakess, the car down l then slow
20
If the p playe y r’s ca c r is in first place, the en disp play message ‘You’ u re in n the lead!’
Sortt it ou ut
More r or r less Some decisions are made in progra ams using different symbols to compare data. These include the greater than > and lesser than < symbols, which are e used to compare numbers. For exam mple, a program to grade the results out of 10 in a child’s spelling test might look like this:
n be sorted out by making decisions. For example, a program might com mpare different numbers to work out which are bigger and which are sma aller. A series of decisions can be sh hown in a branching tree diagram. The one below shows the decisions an algorith hm could make when sorting out a list off objects.
Spelling Test Code est score 8 If spelling te t!’ then print ‘Brillian and End Program
Is it a toy?
ut Keep Trying’ Print ‘Good Bu and End Program
No
Does it have legs?
No
Yes
It’s a ball
It’s a teddy
Does it have a handle?
No
Yes
Answers on page 31
Challenge: Which scores out of 10 would earn the ‘Good But Keep Trying’ mark in the above code and which would earn a ‘Brilliant!’?
Yes
It’s a cushion
It’s a mug
th i w o
G w o l e th F Programmers need to think through all the possible things that can happen in an algoritthm or program and check that all the parts work in the right way and in the right order.
Follo ow the flow chart Many coders use a diagram m called a flow chart to map out their a algorithm or program. This helps them tto find errors and make improveme ents. A flow chart can contain fou ur different shapes or symbols, including an oval, rectangle, diamond d and parallelogram. These are co onnected by arrows to show the differe ent stages and flow of informatio on in a program. Each shape or sy ymbol means a different thing.
22
Flow Chart Symbo ls
Terminator
GAME OVER
Oval shapes show th e start or end of a whole program or just part of a program.
2 +2=4 Process R ctangular shapes Re sh ho ow thatt something happens, such as numbers being adde d together.
Decision
?
Diamond sh hapes show where a program makes a de cision. This is usually a simple deci sion such as ‘yes’ or ‘no’ or ‘true’ or ‘false’. TER PLEASE ENT NAME R NAM UR YOU
Inp In put/Output Parallelogram shapes either mean that the program ac cepts an input like the click of a co mputer mouse or outputs data such as displaying a message or picture on screen.
STRETCH YOURSELF
Flow w charts i action in ti Here is a simple flow chart to show an algorithm for how a player makes a move in a game of Snakes and Ladders.
Fix the Flow Chart
IK out why a lamp isn’t working. There are so me K + pieces of circled text go in each gap? Lamp doesn’t work
Start
Bulb burned o ut?
No Lamp plugged in?
Throw dice Yes
Yes
Move the counter
Replace bulb
No Repair lamp
Yes
Plug in
lamp
Slide down the snake
Landed on snake head?
Answers on page 31
No
COMPUT E
Yess At bottom of ladder?
Climb up ladder
No
End
Hero!
Frank Bunk er DQHQJLQHH Gilbreth ZDV U PDNLQJMRE ZKRHQMR\HG V DVSRVVLEO DVVLPSOH H )UDQNLQWU ,Q ºUVW»RZF RGXFHGWKH RXWZRUNHU KDUWVWRPDS FKDUWVZRX V±MREV)ORZ OG SRSXODUZL ODWHUEHFRPH WKFR SURJUDPPHU PSXWHU V
R
g n i Go
y p o Lo Computers are brillian nt at performing the same task over and over again withou ut making any mistakes. Lots of computer programs take advanttage of this to g get jjobs done.
ad Loop L oops ps an and n variabless The repeating parts of a program are called loops. These often use little stores of data called variables. A variable’s value can alter and b be used to count things in a program.
Loop Turn round Shout: “I’m feeling dizzy” Loop
The e instructionss in a loop willl hap ppen again an nd again as long as tthe loop conttinues.
Countt on us C Loop ps are use eful for counting events or thing gs, espec cially when they are used with variable es that keep track of how many y times ssomething has happened. The lo oop belo ow counts down the seco onds untill a rocket lifts off. Each tiime the prog gram goes through th he loop, the value of the variable SSeconds goe es down by one. The lo oop ends on n lift-off – this is when the variable Seco v onds on n equals zero.
Co ountdown! Computers use variables in a prog gram m to remember things such as a play yer’s score in a game. A variable is give en a name and is a sort of box that can hold information such as a numbe er or a series of letters. This is known as a string. So, a variable to store your age might be age=9 and another could be name=’James’. Variables can be changed by code in the program.
24
Seco eco conds = 60 Repe eat Sec econd ec conds = Seconds -1 Sho ow o on screen: Seconds Until S Seco onds = 0
In a loop p Ten Items Or Fewer S Some loops l continue ti for f as long as the program runs. These are called infinity loops. Other loops, like the countdown loop on page 24, are told to repeat a set number of times. Conditional loops are another type of loop. They keep repeating the steps in the loop until something else happens. For example, this algorithm for a shop checkout scanner only allows 10 items or fewer to be scanned. If more are attempted, tt t d th then th the scanning loop ends.
B-/ N is a variable. It equals the number of items scanned. It is set to zero to start with because nothing has been scanned. Loop Scan item _ " B-BA One is added to the number of items scanned.
If N > 10, ring bell and display ‘No more than 10 items!’ and Leave Loop Loop Again
STRETCH YOURSELF Fix the Time
Minutes-/
Z
[ Here is a loop that is -/ rs ou H k part of a digital cloc king Z -Z A program. It’s not wor op Lo s ow sh properly because it [ -[ A . :67 01 as \Z ->/""I the time 02:07 hich Can you work out w -/ d
-#$"I [ [ \ of the three numbere lines below should line replace the circled \Z ->/"I m ra og pr e th to get A -/[ -[ working properly? ->/"I Z #\Z
Z -[
]\Z ->^"I
Answers on page
31
s ’ g u B A Life
Only some programs work the very first time. Programmers expect erro ors to happen. These errors are known as bugs. Gettin ng rrid of bugs in a program is i called debu c ugging.
Chec ck and test Some programming errors are justt typing mistakes such as keying in the wro ong number or misspelling a command d. These are often spotted by carefully che ecking all the program code. Other errorss, though, are more complicated an nd may take a long time to solve. Programmers often break their pro ogram down into small parts and then run and test each part to try and find the proble problem em.
26
Testing times Te esting takes place throughoutt the time a computer program is be eing d developed. Sometimes, compu uter users a ask are ked to test out the progra ams. They act as beta testers and report b back any b gs or problems bug blems that they ffind d.
Catch the B C Bug
IK program for playing ‘Tag’ or ‘It’ . But one of the arrows is in the wrong pla ce for the program to work properly. Can you work out which arrow is wrong, and where it should go?
Start
Launch fa ailure S Some bugs b iin programs can be devastating. A bug in th he guidance computer of an Ariane 5 space rocket mad de the rocket veer off target a and finally self-destruct just a miinute nute after ft lift-off in 1996.
Choose one person to be the chaser
Are you the chaser?
Yes
N No
TRUE STORY
Run away from the chaser
G s,QDGHD Moth Bugs XVHGDVZLWFKWR PRWKFDX KH WK H PDOIXQFWLRQLQVLG QH RQ +DUYDUG0DUN,,¬ V XWHUV RIWKHºUVWFRPS FN WXF URJUDPPHUVVW 7KHSU H WK WKHPRWKLQWR WZDV ERRN,W JE RJ OR FRPSXWHU±VO J± °EXJ ºUVW° º V ±V J± FRPSXWLQJ
Chase the other children
No Has the chaser caught you?
Have you caught someone?
Yes
You are not the chaser anymore
Yes
Answer on o page 31
No
Now you are the chaser
Coding
s r e e Car
Think you might become a whizz at computer coding when you get older? If so, then there may be some great jobs for you when you grow up.
Work king toge ether r In tthe he past past, computer programs and a code were often written by only y one person. Today, many major applic cations and games need dozens or even n hundreds of people to build them m. Some people work out what the program should do, while others write and test the code. Many other co oders work on existing programs, writing g code for new features or debugging gging problems with the latest program m.
28
ER COMPUT
Hero!
Jack Dorsey ey y Z ZDV DV IDVFLQD ID DVFLQDWHGE\FR RGLQJ DV VDFKLOG,Q 'RUV VH\DQGKLVEX XVLQHVV SD DUWQHU%L]6W WRQH ZUR RWHWKHºUVWYH HUVLRQ RIWKH7ZLWWHUVRFLDO RI WKH 7ZLWWHU VRFLDO V QHWZRUNLQJDSSLQMXVW WZRZHHNV2YHU PLOOLRQ°WZHHWV±DUH QRZVHQWHYHU\GD\
Jack Dor se
y
Young g co oders – just like you!
Think big g Th programs you use on a com The mputer are often huge projects. A typica al iPhone app may have 30,000 lin nes of code, while a complex comp puter game can have over a million! Even bigger is the Windows 7 operatin ng system, which contains about 40 million lines of code. Phew!
Computer coding can be a job b for life. For example, Markus ‘Notch’ Pe ersson was a programming whizz-kid. He wrote his first computer game using BA ASIC when he was only eight years old! When he grew up, Markus wrote e games for Jalbum. He left his job to create his own hit h game – Minecraft.
TRUE STORY PH Fun7KHJD e d i W d l r Wo Q FUHDWHGL 7HWULVZDV HQJLQHHUFDOOHG WHU E\DFRPSX WQRYD7HWULVKDV L M WR $OH[H\3D SURJUDPPHG H U Q H H E H V VLQF IFRPSXWHU R V W R O Q R ZRUN WDEOHWV SKRQHVDQG
STRETCH YOURSELF Write a Computer Program
Can you think of a computer program that would make your life easier? Try to sketch t out all of its different parts.
ese questionss: Then, ask yourself th rate? ram operra How would the prog
tto know?
to use it? in advance?
y r a s los
G
l orithm A set of steps alg that are followed in order to solve a problem or perform a task.
database A program that allows people to store huge amounts of information on computers with ease.
beta tester A person who tests a computer program that is almost finished to try and find any bugs or problems. binary Also known as base 2, binary is a number system that contains just two digits: 1 and 0. browser A type of computer program used by people to view websites on the World Wide Web. coding Writing the lines of code in a program that make a computer or other device work. code selection When a program is told to run a particular piece of code after making a decision, such as running the code that says ‘Game Over’ and giving a final score when the program decides the game has ended. compiler A computer program that converts instructions written in a programming language into code that a computer can understand and act on.
30
debugging To identify and remove errors in a computer program. decimal Also known as base 10, decimal is the number system that you use every day. It contains the digits, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.
parallelogram A shape with opposite sides that are parallel and also equal in length. programmer A person who writes computer code and programs, either for fun or as a job. smartphone Powerful mobile phone that contains a mini computer which allows users to view videos, listen to music and run lots of different programs.
decomposing Breaking down a complicated task into smaller parts or steps, making it easier to understand and write code. flow chart A type of diagram that maps out the actions and decisions that occur within a program or part of a program. input Data or commands that a user enters into a computer using a keyboard or by pressing a touchscreen on a tablet. loop A part of a computer program that repeats the same steps and instructions over and over again. Many loops are conditional – they continue until a condition is met or an order instructs them to stop. output The results of a computer’s processing and work. Output is often displayed on a screen.
string A type of variable (see below) that stores one or more letters or other characters. subroutine A section of a program which performs a task and can be jumped back to as many times as the whole program needs. variable A location for storing information in a program which can be changed by other parts of the program.
er h t r u s F e c r u o Res Books How Things Work: Electrical Gadgets by Ade Deane-Pratt (Wayland, 2013) Quick Expert’s Guide: Computing and Programming by Shahneila Saeed (Wayland, 2015) Quick Expert’s Guide: Creating an App by Chris Martin (Wayland, 2014) Technology Timelines: Digital Technology by Tom Jackson (Franklin Watts, 2015)
Websites https://www.commonsensemedia.org/lists/coding-appsand-websites A great page containing links to lots of different computer activities and languages to help you learn about coding. https://www.helpkidscode.com/ A website for parents, teachers and older children. http://learn.code.org/hoc/1 A video tutorial which helps you use the Blockly coding language to create a simple program. http://www.light-bot.com/hocflash.html Have fun programming an on-screen robot called Lightbot. http://www.scratch.mit.edu Learn more about coding by creating programs starring Scratch the Cat and other fun characters. http://www.wordfreegames.com/game/binary-game.html A groovy game to help teach you how to use binary numbers.
Answers e8 page pag mal to ecim Dec eD nge ang Cha Ch y narry: Bina Bi 0 00 000 6 = 100 16 01 0001 7 = 100 17 1 01 010 101 21 = 1 e9 page pag !: y!: Spy y Sp ary inar e a Bin ome com Bec Be d and an e d dl d mid m r ur You 6 = Yo ger nge th fin urth our fo d and dexx an inde r our in You 10 = Y r er nge fing fi h rth ourt ffou de ddl mid dexx,, m inde ourr in You 13 = Y r ger inge fin f e ttle tt d lil and an d and b an umb thum our th 20 = You r ger inge in f dle ddle mid mi e 12 page pag e: rtle Turt e Tu the trol th ntro Con Co m ram gra rog ro p O GO LOG LO e The * Th he the t w aw dra dr ld uld wou wo le ngle iang tria ral tr tera ate uila equ eq d) e swer nsw (an (a h fth d fifift and rstt an e fifirs The * Th y say sa h oth bot b ld ould ou s sh ness liline . s ps’. tep te s 00 1 d rd a war orw ‘ or ‘F e 13 page pag kett cke Roc ot Ro bot Rob Ro e ge: eng en hall ha C h ch n unc Lau La o of t est es r he the t re a e Herre He he t s ds and an m mm com e co the th rder n ord d in eed w ll nee ot wi bot rob ro t e ket. ock oc r is his h h ch eac to rea ard rwa forw e fo ove 9 Mov 9. e ce pac pa 1s ghtt e riigh the o th rn tto Turn 10.. Tu 10 d rd a war orw for f e ve Mov 11. Mo 11 e ce pac pa 1s ghtt e righ the o th rn to Turn 12. Tu 12 rd a w orw or f e ve Mov 13.. Mo 13 es ces pac 2 sspa ghtt e riigh the t rn Turn o th 4. Tu 14 d rd a war orw for f e ve Mov 15.. Mo 15 s e ces pac 4 sspa eft e le the o th n tto urn 16. Tu d rd war wa o for f e ve Mov 7. Mo 17 e ce pac spa s 1
8 e 18 page pag e the F x th u Fi You n Yo Can Ca : ? ns? ions ctio ct u stru Inst In g lug h plu batth ut in ba Put 1. P er ter wat wa h i it w h th bat 3. FFilil ba ed ssed ress ndre und u et Get 8. G h batth e ba the o th nto et iint Get 4. G h s ash Wa 5. W h batth e ba the et out of th Get 7. G g u plu p h th bat ba out ou e ake 6. TTak esssed Get dre 2 G 2. e 21 page pag estt ng Tes elliling Spe Sp e ge: eng alllen ha C e de Cod Co d and 6, 7 an ,6 5, , 4 s es ore or c sc e The * Th a n rn ear ea l uld wou 8 wo g’ ing’ yin p Try ep Kee Butt Ke od Bu ood ‘Go ‘G . rk. mark nd 10 and ress 9 a ore sco e sc The * Th t!’’ a t! illilian Bril Br ‘ a n rn ear ea d l u wou wo . rk. mark 3 23 e2 page pag t: harrt: Flow Fl e the ow Cha F x th Fi p’ am lam in g u Plu * ‘P e lue blu the b uld go in the ould sho sh . e. p ape sha sh r lar u gula n ang t cta rec re ut?’ burrned out u b bu ‘Bul * ‘B een gre he the t in o g d u ould sho sh . e. p ape sha sh d ond on d am di 5 25 e2 page pag e: Tim Ti e the me: x th Fix Fi uld ould sho er 2 sh ber umb num n ne Line Li ne. liline d led rcle circ ci e the th e ace ac l p rep re 7 27 e2 page pag g:: Bug the th h c Cattch e Bu Ca tom o to e bot the at w o arro ar e The Th in s i t rt har ha c he t o of t ght righ e.. To ace plac ng pl ong wro he wr th am, ram g ogr pro e the th g u bug deb de intt poin po d l uld hou sho ow rrow rr a hiss th e the th e are ar u you yo w Now ‘No om from fr e the th e s ase Cha Ch ‘ to r er’ s ase cha ch n. en’ dre chilldr er ch her oth ot
x e d n I e electrical circuits 8 a algorithms 30 everyday 6 precise instructions 16–17 ps 18–19 step using different methods 7 b Babbage, Charles 5 base 2 see binary BASIC language 10, 29 beta testers 26, 30 binary 8, 9, 30 8 converting decimal to binary 9 l ima dec to ry bina ing vert con branching tree diagram 21 browser 15, 19, 30 programs 11 bugs beta testers 26 check and test 26 c uage 11 ngu l ng + la C++ code building 10 g 26 ugs f r bu ecking fo che decisions 20 huge projects 29 writting programs 4 code selection 20, 30 coders 4, 6, 10, 17, 19, 22, 28 coding 4, 10, 30 careers 28–9 learning 12 column calculations 9 commands 30 English language 10, 11 robot 13 compiler 10, 11, 30 computer mouse 22 computers and Charles Babbage 5 decision-making 20–21 early 10, 27 electrical circuits in 8 instructions for 4, 16 personal 13 repeating tasks 24 conditional loops 25 countdown loops 24, 25 d data 8, 21, 22, 24, 30 databases 11, 30 debugging 26, 28, 30 decimal 8–9, 30 8 converting decimal to binary 9 l ima dec to ry bina g ing vert con decisions 20–21 decomposing 17, 30 Dorsey, Jack 28
32
f flow charts 30 in action 23 debugging 27 ps 23 filling in gap symbols 22 g games 11, 13, 14, 28 car-racing 20 Minecraft 29 Snakes and Ladders 23 Tetris 29 Gilbreth, Frank Bunker 23 h Hopper, Grace 11 i IF ... THEN statement 20 infinity loops 25 inputs 22, 30 j Jalbum 29 Java language 11 k keyboards 30 du program 13 Kod l LOGO language 12 loops 30 conditional 25 countdown 24, 25 infinity 25 and variables 24 Lovelace, Ada, Countess of 5 m mobile phones 29, 30 moth bugs 27 n number systems 8 o outputs 22, 30 p Pajitnova, Alexey 29 Papert, Seymour 12 Persson, Markus ’Notch’ 29 27, 30 programmers 4, 5, 7, 22, 23, 26, 3 10–1 es uag lang g min ram prog 6 4, s program beta testing 26 browser 11 the first 5 Python program 13
r recipe algorithm 7 robots Bee-Bots 13 Lego Mindstorms 13 b t 19 Lightbo precise commands 16 Roamers 13 Turtle 12 s Scratch programs 13 blocks 15 screen 14 sprites 14 website 15 smartphones 4, 5, 11, 30 SQL language 11 squash-drink algorithm 6 steps in an algorithm jumping around 18 subroutines 19, 30 Stone, Biz 28 strings 24, 30 subroutines 19, 30 t tablets 5, 11, 29 v variables 24, 30 w Watson, Thomas 5 ges 11 web pag World Wide Web 30
Plenty of Books to
INFORM AND ENTERTAIN
For a full range of titles visit
WWW.WAYLANDBOOKS.CO.UK • Free printable downloadable resources • • Titles which fit the changes in the new curriculum • S T MISST ’ N O D LATE THE WS! NE
FOLLOW US ON www.facebook.com/waylandbooks www.twitter.com/waylandbooks