Ian Sinclair - Working With MSX BASIC

222

Transcript of Ian Sinclair - Working With MSX BASIC

Otherbooksof interest TheMSXGamesBook JimGregory 0003830837 Working with SX BASIC Ian Sinclair COLLINS 8 Grafton Streer, London W I Otherbooksof interest TheMSXGamesBook JimGregory 0003830837 Working with SX BASIC Ian Sinclair COLLINS 8 Grafton Streer, London W I CollinsP rofessi onalandTechnicalBooks WilliamCollinsSons&Co.Ltd 8GraftonStreet,LondonW I X3lA FirstpublishedinGreatBr ita inby CollinsProfessionalandTechnicalBooks1985 Distri butedint heUnitedStatesof America bySheri danHouse,Inc. Copyright1985IanSincl ai r BritishLibraryCat aloguinginPublicationData Sinclair,Ia nR. WorkingwithMSXBASIC. I.Basic(Computerpr ogramlanguage) 2.Mi crocomputers- Pr ogramming 1.T itle 001.64'24QA76.73. B3 ISBN0-00- 383103- 5 T ypesetbyV&MG raphi csltd,Aylesbury,Bucks PrintedandboundinGreatBritainby Mackaysof Chatham,Kent Allrightsreserved .Nopartof thi spublicationmay berepr od uced,storedinaret rieva lsystemort ransmitted, inanyform,orbyanymeans,electronic,mechanical ,photocopyi ng, recordingorotherwise,withoutthepriorpermissionof the pu blishers. Contents Preface Vll WhereDo WeStart? 1 2InputsandOut puts 10 3Quantitiesof Numbers 29 4StringsAttached 44 5Repeat ingYourself 61 6 MenusandSubrout ines 79 7 SpecialEffectsandGeometricalSha pes 97 8 DRAWGraphics l IS 9 IdentifiableFlyingObjects 128 10 SoundsUnlimited 143 IICassetteDataFiling 162 12 Editing,Fault-tracingandMiscellany 182 AppendixA: TVandCassetteHints 193 AppendixB:CassetteHeadAdj ustment 201 AppendixC:SomeOt herCommands 203 Index 205 viiiPreface MSX manufacturers willalsooffer cassette recorders, though if you have a recorderalreadyitcanprobablybeused.Many of theMSXmanualssay verylittleabouttuningaTVreceivertothecomputer'ssignals,or about checkingandadjustingcassetterecorders,andsothesetopicshavebeen dealtwithinAppendixA. Another important point about MSX isthat the system can be expanded; moreoveryouarenotcompelledtobuyproductsfromjustone manufacturer.Manycomputermanufacturersinthepastdesignedtheir machines so that it was almost impossible to use additional equipment from anyothersupplier.Thismeantthatwhenyoudecidedtoscrapthe computer,youhadto scrap everything elseaswel l.Younolonger haveto acceptthissituat ion,becauseMSXusesstandardisedconnectionsand signals.AnycomputingequipmentthatyoubuyforoneMSXmachine shouldbeusableonanyotherMSXmachine.Inaddition,if you already have aprinter which isfittedwiththe standard Centronics connection you willbeabletouseitwithyourMSXcomputer;allyouwillneedisa connectingcable. If you have used another type of computer, perhaps at school, at work,or athome, t hen you will readily understand the advantage of the MSX system fro mreading this book. In particular, you will appreciate the abi lity to carry out precise arithmetic, and to have easy control over sound and graphics. As yourprogramming knowledge advances,youwillfindthat MSXhaseven more to offer,particular ly if you are interested in lists and in filing data. For beginneror expertaJike,MSXhasabrightfuture. Iwouldliketo emphasise that thisbook waswrittenwhile Iwas using a Toshiba MSX computer, and that the listing of programs in this book were obtainedfromanEpsonprinter t hat wasconnectedto the MSX computer. Thismightseem to be an unnecessary claim, but manybooks still appear in whichtheprogramlistingshavebeenretyped,witherrorsappearingin manyofthem.Everyprogramwhichappearsinthisbook,andevery exampleofprogrammingcommands,hasbeentestedontheMSX computerwhichIhavehereinfr ontofme.Nothinghasbeencopied untested from t hemanual, and where a command has operated in a way that isnotobviousfr omthemanualdescriptionIhavepointedoutthe difference.Onepri cethatIhavehadtopayforthishasbeenthe disappearanceof t hesignsfromseveralli stings,notablyinFigs2.1 8to 2.20.Thisisbecauset hepoundcharacterwhichappearson the computer screen does not appear on my printer, but I have noted in the captions where thepoundsignshouldbetypedin.Allof the screen displays which Ihave describedwereobtainedonaFidelityTV/ monitor,whichwasusedasa normalTVreceiver. Asal ways,Iamgreatlyindebtedtomanypeoplewhohavemadethis bookpossible.ThemachinewasprovidedbyToshiba(UK)Ltd.,and RichardMilesof CollinsProfessional & Technical Books worked tirelessly to ensure thatIhadthisMSX computer on my desk assoon aspossible. I Prefaceix owe a special debt of gratitude to RichardYardley, of Spectravideo Ltd. He alonewasabletogetmeaprintercable fortheMSX computer at at ime when there appeared to be only two such items in the country. Among many ot hersatCollinsProfessional&TechnicalBooks,RichardMiles,Janet Murphy and Sue Moore worked wonders with my manuscript, and the most efficient team of typesetters and printers that 1 know operated to produce the book inrecord-breaking time. I a m sure that the result of all this work will be a bookthatwillmatchthecapabilitiesof yourMSXcomputer. IanSinclair CollinsP rofessi onalandTechnicalBooks WilliamCollinsSons&Co.Ltd 8GraftonStreet,LondonW I X3lA FirstpublishedinGreatBr ita inby CollinsProfessionalandTechnicalBooks1985 Distri butedint heUnitedStatesof America bySheri danHouse,Inc. Copyright1985IanSincl ai r BritishLibraryCat aloguinginPublicationData Sinclair,Ia nR. WorkingwithMSXBASIC. I.Basic(Computerpr ogramlanguage) 2.Mi crocomputers- Pr ogramming 1.T itle 001.64'24QA76.73. B3 ISBN0-00- 383103- 5 T ypesetbyV&MG raphi csltd,Aylesbury,Bucks PrintedandboundinGreatBritainby Mackaysof Chatham,Kent Allrightsreserved .Nopartof thi spublicationmay berepr od uced,storedinaret rieva lsystemort ransmitted, inanyform,orbyanymeans,electronic,mechanical ,photocopyi ng, recordingorotherwise,withoutthepriorpermissionof the pu blishers. Contents Preface Vll WhereDo WeStart? 1 2InputsandOut puts 10 3Quantitiesof Numbers 29 4StringsAttached 44 5Repeat ingYourself 61 6 MenusandSubrout ines 79 7 SpecialEffectsandGeometricalSha pes 97 8 DRAWGraphics l IS 9 IdentifiableFlyingObjects 128 10 SoundsUnlimited 143 IICassetteDataFiling 162 12 Editing,Fault-tracingandMiscellany 182 AppendixA: TVandCassetteHints 193 AppendixB:CassetteHeadAdj ustment 201 AppendixC:SomeOt herCommands 203 Index 205 Preface MSXis the name for asetof standards to which many computers are being constructedatpresent,andtowhichmanymor e willbeconstructedint he future.Untiltheadventof MSX,atapewhichhadbeenrecordedbyone makeof machinecouldnotbeusedonany othermachine. Worse sti ll,t he programmerof onemakeof machinewouldfinditquite difficultt o switch toanothermachine wit houtrel earning thelanguage.MSXhas at long last ended thisridi culous situation, so that anyone whobuys an MSX computer willbeableto exchangetapesandprogramideaswit h anybody elseus ing MSX.Themanufacturersmaybedifferent,butthemachinesworkin exactlythesame way.An additionalbonusfor the retailers isthat many of t heMSX machinesare manufacturedbycompanies who are respect ed and trust ed,withalonghistoryofsuccessinradi o,TVandhi-fi. If youhave bought thisbook as a guide to MSX before buying, a few hints onmachinesmaybehelpful.Thoughallof t hemachineswi llrun the same tapes, andbeprogrammed in the same way, they are not ident ical.Some,for example,havebett erkeyboardst hanot hers.Foranyonewhodoesany more wit h acomputer t han play games, the provi sionof agood keyboard is veryimportant.Somemachinescanbeconnectedt omanymoredevices t hanot hers.Thebusinessuserofacomputerwi llwanttoconnectupa printer anda dis k dr ive,and thi s isprovided for in all MSX machi nes.If you wanttouseyourcomputer tocontrol amusi csynthesiserortoworkwit h picturesfromavideocamera,however, youmay findt hatsomemachines arebetter sui tedtothis thanothers. Very often,you willfindthat t he items t owhichyourMSX computer can be connectedrefl ect the special interests ofthemanufact urer. To makeupacomputer systemyouneedt heMSX computer,a cassette recorder,andaTVreceiver or monitor.AllMSX machi nesprovide colour signalstocolourTVreceivers,andsoundsignalsalso.Similarly, allMSX machinescanbe usedwit hmonitors.Amonitor is a form of TVwhichhas been designedtotakesignalsdi rect lyfrom a computer or a videorecorder, rather t han from an aerial. It gives amuch clearer picture than you can ever getwi thaTVreceiver.ManymanufacturersofMSXcomputerswill pr obablyoffercolourmonitorsinaddit ion t ot hecomputers.Mostof the Preface MSXis the name for asetof standards to which many computers are being constructedatpresent,andtowhichmanymor e willbeconstructedint he future.Untiltheadventof MSX,atapewhichhadbeenrecordedbyone makeof machinecouldnotbeusedonany othermachine. Worse sti ll,t he programmerof onemakeof machinewouldfinditquite difficultt o switch toanothermachine wit houtrel earning thelanguage.MSXhas at long last ended thisridi culous situation, so that anyone whobuys an MSX computer willbeableto exchangetapesandprogramideaswit h anybody elseus ing MSX.Themanufacturersmaybedifferent,butthemachinesworkin exactlythesame way.An additionalbonusfor the retailers isthat many of t heMSX machinesare manufacturedbycompanies who are respect ed and trust ed,withalonghistoryofsuccessinradi o,TVandhi-fi. If youhave bought thisbook as a guide to MSX before buying, a few hints onmachinesmaybehelpful.Thoughallof t hemachineswi llrun the same tapes, andbeprogrammed in the same way, they are not ident ical.Some,for example,havebett erkeyboardst hanot hers.Foranyonewhodoesany more wit h acomputer t han play games, the provi sionof agood keyboard is veryimportant.Somemachinescanbeconnectedt omanymoredevices t hanot hers.Thebusinessuserofacomputerwi llwanttoconnectupa printer anda dis k dr ive,and thi s isprovided for in all MSX machi nes.If you wanttouseyourcomputer tocontrol amusi csynthesiserortoworkwit h picturesfromavideocamera,however, youmay findt hatsomemachines arebetter sui tedtothis thanothers. Very often,you willfindthat t he items t owhichyourMSX computer can be connectedrefl ect the special interests ofthemanufact urer. To makeupacomputer systemyouneedt heMSX computer,a cassette recorder,andaTVreceiver or monitor.AllMSX machi nesprovide colour signalstocolourTVreceivers,andsoundsignalsalso.Similarly, allMSX machinescanbe usedwit hmonitors.Amonitor is a form of TVwhichhas been designedtotakesignalsdi rect lyfrom a computer or a videorecorder, rather t han from an aerial. It gives amuch clearer picture than you can ever getwi thaTVreceiver.ManymanufacturersofMSXcomputerswill pr obablyoffercolourmonitorsinaddit ion t ot hecomputers.Mostof the viiiPreface MSX manufacturers willalsooffer cassette recorders, though if you have a recorderalreadyitcanprobablybeused.Many of theMSXmanualssay verylittleabouttuningaTVreceivertothecomputer'ssignals,or about checkingandadjustingcassetterecorders,andsothesetopicshavebeen dealtwithinAppendixA. Another important point about MSX isthat the system can be expanded; moreoveryouarenotcompelledtobuyproductsfromjustone manufacturer.Manycomputermanufacturersinthepastdesignedtheir machines so that it was almost impossible to use additional equipment from anyothersupplier.Thismeantthatwhenyoudecidedtoscrapthe computer,youhadto scrap everything elseaswel l.Younolonger haveto acceptthissituat ion,becauseMSXusesstandardisedconnectionsand signals.AnycomputingequipmentthatyoubuyforoneMSXmachine shouldbeusableonanyotherMSXmachine.Inaddition,if you already have aprinter which isfittedwiththe standard Centronics connection you willbeabletouseitwithyourMSXcomputer;allyouwillneedisa connectingcable. If you have used another type of computer, perhaps at school, at work,or athome, t hen you will readily understand the advantage of the MSX system fro mreading this book. In particular, you will appreciate the abi lity to carry out precise arithmetic, and to have easy control over sound and graphics. As yourprogramming knowledge advances,youwillfindthat MSXhaseven more to offer,particular ly if you are interested in lists and in filing data. For beginneror expertaJike,MSXhasabrightfuture. Iwouldliketo emphasise that thisbook waswrittenwhile Iwas using a Toshiba MSX computer, and that the listing of programs in this book were obtainedfromanEpsonprinter t hat wasconnectedto the MSX computer. Thismightseem to be an unnecessary claim, but manybooks still appear in whichtheprogramlistingshavebeenretyped,witherrorsappearingin manyofthem.Everyprogramwhichappearsinthisbook,andevery exampleofprogrammingcommands,hasbeentestedontheMSX computerwhichIhavehereinfr ontofme.Nothinghasbeencopied untested from t hemanual, and where a command has operated in a way that isnotobviousfr omthemanualdescriptionIhavepointedoutthe difference.Onepri cethatIhavehadtopayforthishasbeenthe disappearanceof t hesignsfromseveralli stings,notablyinFigs2.1 8to 2.20.Thisisbecauset hepoundcharacterwhichappearson the computer screen does not appear on my printer, but I have noted in the captions where thepoundsignshouldbetypedin.Allof the screen displays which Ihave describedwereobtainedonaFidelityTV/ monitor,whichwasusedasa normalTVreceiver. Asal ways,Iamgreatlyindebtedtomanypeoplewhohavemadethis bookpossible.ThemachinewasprovidedbyToshiba(UK)Ltd.,and RichardMilesof CollinsProfessional & Technical Books worked tirelessly to ensure thatIhadthisMSX computer on my desk assoon aspossible. I Prefaceix owe a special debt of gratitude to RichardYardley, of Spectravideo Ltd. He alonewasabletogetmeaprintercable fortheMSX computer at at ime when there appeared to be only two such items in the country. Among many ot hersatCollinsProfessional&TechnicalBooks,RichardMiles,Janet Murphy and Sue Moore worked wonders with my manuscript, and the most efficient team of typesetters and printers that 1 know operated to produce the book inrecord-breaking time. I a m sure that the result of all this work will be a bookthatwillmatchthecapabilitiesof yourMSXcomputer. IanSinclair ChapterOne Where Do We start! WelcometoMSX computi ng. By thistime, youdon't havetobetoldhow well-designedandconstructedyournewMSXcomputeris.Whatyou probably want toknow,however,is just how youcan getmore out of it.If you intendto use the computer asyou use a washing machine, running only programswhicharebuilt-inorwhichyoucanbuy,thenthemanualwhich comeswit ht hemachine willserve you well.But buying acomputer andnot programmingitforyourself islikebuying aPorscheand getting someone elsetodriveit.ThisbookisallabouthowyoucanmakeyourMSX computer dowhat youwant, so t hat you can make fulluse of all these keys thatyouhavepai dfor. Tostartwi th,justwhatcanthecomputerdoforyou?Youmayhave bought itt oplay games,as many owners do. Gamesnowadays are desi gned byprofessionals,usingmuchlargercomputers,soyoucan't reallyhope to comeup with anew and earth-shattering game with asmall machine. What you can do, though, isto use the machine for your own purposes. You might wanttokeeptrackof themembersof your Rugby Clu b,or thepurchases fromyourmai lordercatalogue.Youmightwantt odeviseeducati onal gamesforyourchildren;gameswhichare suitedtot heirparticularneeds. YoumightwanttorunalocalCameraClub,keeptrackof shareson the Stock Exchange,analyse what your car costs, check your income tax ... the listisendless.Whateveryourowninterestis,whet herit'stracingyour ancestorsorcataloguingthewor ksofalong-deadwriter,you' llneeda program. A computerisabrainlessmachine,whatever anyone says. W hat makes it workisasetof instructionsthatwe callaprogram. Youcanwritesucha program for yourself,so that it doeswhat you want.Now if your program is useful to you, it might possibly be interesting to someone else. You might be theonlypersonusingthecomputertokeepthescoresandrecordsof the Litt le Tiddleworth Darts Club,but there couldbe alot of ot her people who wouldliketotryout yourprogram fortheirownuses . That'swhereMSX comesin.If youhavewrittenaprogramforoneMSXcomputer,and recordeditontape or ondisk,thenitshouldbeusableon any other MSX computersolongasthereisenoughmemoryinthatmachinetoholdthe ChapterOne Where Do We start! WelcometoMSX computi ng. By thistime, youdon't havetobetoldhow well-designedandconstructedyournewMSXcomputeris.Whatyou probably want toknow,however,is just how youcan getmore out of it.If you intendto use the computer asyou use a washing machine, running only programswhicharebuilt-inorwhichyoucanbuy,thenthemanualwhich comeswit ht hemachine willserve you well.But buying acomputer andnot programmingitforyourself islikebuying aPorscheand getting someone elsetodriveit.ThisbookisallabouthowyoucanmakeyourMSX computer dowhat youwant, so t hat you can make fulluse of all these keys thatyouhavepai dfor. Tostartwi th,justwhatcanthecomputerdoforyou?Youmayhave bought itt oplay games,as many owners do. Gamesnowadays are desi gned byprofessionals,usingmuchlargercomputers,soyoucan't reallyhope to comeup with anew and earth-shattering game with asmall machine. What you can do, though, isto use the machine for your own purposes. You might wanttokeeptrackof themembersof your Rugby Clu b,or thepurchases fromyourmai lordercatalogue.Youmightwantt odeviseeducati onal gamesforyourchildren;gameswhichare suitedtot heirparticularneeds. YoumightwanttorunalocalCameraClub,keeptrackof shareson the Stock Exchange,analyse what your car costs, check your income tax ... the listisendless.Whateveryourowninterestis,whet herit'stracingyour ancestorsorcataloguingthewor ksofalong-deadwriter,you' llneeda program. A computerisabrainlessmachine,whatever anyone says. W hat makes it workisasetof instructionsthatwe callaprogram. Youcanwritesucha program for yourself,so that it doeswhat you want.Now if your program is useful to you, it might possibly be interesting to someone else. You might be theonlypersonusingthecomputertokeepthescoresandrecordsof the Litt le Tiddleworth Darts Club,but there couldbe alot of ot her people who wouldliketotryout yourprogram fortheirownuses . That'swhereMSX comesin.If youhavewrittenaprogramforoneMSXcomputer,and recordeditontape or ondisk,thenitshouldbeusableon any other MSX computersolongasthereisenoughmemoryinthatmachinetoholdthe 2WorkingwithMSX BASIC program.MSXisasystemthatisusedbymanycomputermanufacturers forjustthisreason. Whatisacomputer,then? Theshort answer is thatit'samachine which canorganise information for you.Give it a set of names and addres ses, and it will store them, arrange t hem into alphabet ical order, produce the address for a name t hat you type, and so on. Give it a list of names and payments to a clu b,anditwillgiveyoualistofwhopaidhow much and whostillowes what.Give it a group of numbers in answer to quest ions about your earnings and expenses, andit willshow youyour correct tax code.Does t hissound like abrai nJessmachine? If it doesn't, that's because all ofthe organisation is doneunderthecommandof aprogram.Theprogramiswhat wecallthe soft wareof themachine. Without a suitable program, the computer can do nothing.Themachineitselfist hebrainlessbit,thecleverpartisthe program.Sohowdoyougoaboutwritingaprogram? It isn't asdifficultas you might think. The reason ist hat t here has been a great deal of progress in this r espect in the last twenty years. Many years ago computerswerebigmachineswhichhadtobeprogrammedbyskilled peoplewhounderstoodthenumbercodesystem- calledmachinecodethatthecomputerused.Asti mewenton,programmi nglanguageswere invented.Aprogramminglanguageisawayof instructing acomputer by usingcommandwordswhichareEnglishwords .Evenbeforemicrocomputersweredreamedof,therewereseveraloftheseprogramming languages,butthemost importantone forusisBASIC. BASIC isshort fo r BeginnersAll-purposeSymbolicInstruct ionCode.Itwasinventedat Dartmout hCollege,USA,asawayofteachingcomputerprogramming. Si nce then, ithasspread like wildfi re to become the programming language thatisusedforeachandeveryhomecomputer.It' sstillagoodlanguage forbeginnersint hesensethatit'seasytolearn,butithas alsodeveloped intoalanguagethatgivesyouagreatdealofcontroloveryour computer. YourcomputerusesaspecialvarietyofBASICwhichiscalledMSX BASIC.It'soneoft hemostuptodate varietiesof BASIC, andyetithas beendevel opedfr omoneoft hefirstversionsofBASICusedinsmall computers;MicrosoftBASIC.WhatthatallboilsdowntoisthatMSX BASlC iseasy t ouse, reliable, and yet capableof getting the best fr om your computer.UnliketheoldervarietiesofBASIC,t oo,itwi llworkonany MSXmachine.Canyouimagineaworldinwhichyourrecordswouldn' t playonyourneighbour' shi-fisystem?Wouldyoubuyacassette playerif youknewthatonlyonemake of cassettecouldbe usedwith it? That's the state thatcomput ing was inbefore MSX. Now for anyone who doesn't have an MSXmachine,that'st he wayitstillis,but for you, t hings are different. Your computercan use a tape or disk that was recorded by any other MSX computer.Anyone else whohasan MSX computer can make use of one of your tapes or disks. That's the way it should havebeen inthe first place, but it has taken MSX to do it.Hyou have never tu ned a TV receiver, or adjusted WhereDoWeStart?3 a cassette recorder, there's help for you in Appendices A and B at the end of thisbook. BASIC foundations TheBASI Clanguageisbuiltli keanyot herlanguage, with vocaculary and syntax.Vocabulary meanst hewordst hat are used to make t hings happen. Syntaxmeanst hewaythatyouhavetousethewords.Likeanyot her language,BASIChasruleswhichhavetobelearned.Whatmakesitso much easier for you to learn is that the words are mainly English words, and therulesare simple.Moreover, your computerwill tell youwhen you have disobeyedtherules! To learn about BASIC,then, youhave to learn what anumber of words mean.Thereareaboutonehundredofthesewords,andthemeaningof mostof themisobvious. In addition, you must learn the correct way to use eachword.Thisiswhere you really come up agai nst the 'brainless machine' bit.The computer canmake use of a command which usesthe correct word in t he correct way. If you use the wrong word, spell the word wrongly,or use it in thewrong way, t hemachine can' t do anyt hing - so it stops. When it does this, amessage will appear on t he screen to tell you what has happened. This iscalled an error-l1'zessage, and from what it says, you shouldbe able to fi nd whatwentwrong. If that makesit sound simple,that' s because it is simple, andthat's why it needstobelearned.Suppose,forexample,youhadaforeignfri endwho understoodonlyaboutonehundredwordsof English.Howwouldyou makehim understand,usi ng only the words he knows, that you want him to dosomet hingli kearrangewordsinalphabeticalorderorfindhowmany membersof the dominoesclub havepaid their subscripti ons? The answeris thatyouhavetobreakupthesecomplicat edact ionsintoalotof si mple steps.Yout henhave todescribeeach step in the words that your hundredword friend underst ands.There's one big difference here, though. Ahuman whoknowsahundredwordsof alanguagewillpickupot her wordsvery quickly.Acomputer does n't, so far,have thisability. Every ins truction has to be made out of these important command words, the keywords as we call them.Aprogramconsistsofanarrangementof thesekeywordsinsucha wayt hatsomet hi ngusefulisdone.Aprogrammightbeeducat ional, amusing,forbusinessorleisure,workingwi thwordsorwithnumbers; whatever you want itto be.Whateveritis,though, it st illhasto make use of t hesekeywords ,becausethat'sallthatthemachinecanunderstand.You can'ttypeinstructionslike'Whoorderedadozen spob-tackers?'or 'What willmypaymentsbeif Ipaybackonefifthof themortgage?' . Theseare questionsforhumanswithhumanbrains,notforcomputers.Computers havememory.Theycan store informationand t heycan store instructions. 2WorkingwithMSX BASIC program.MSXisasystemthatisusedbymanycomputermanufacturers forjustthisreason. Whatisacomputer,then? Theshort answer is thatit'samachine which canorganise information for you.Give it a set of names and addres ses, and it will store them, arrange t hem into alphabet ical order, produce the address for a name t hat you type, and so on. Give it a list of names and payments to a clu b,anditwillgiveyoualistofwhopaidhow much and whostillowes what.Give it a group of numbers in answer to quest ions about your earnings and expenses, andit willshow youyour correct tax code.Does t hissound like abrai nJessmachine? If it doesn't, that's because all ofthe organisation is doneunderthecommandof aprogram.Theprogramiswhat wecallthe soft wareof themachine. Without a suitable program, the computer can do nothing.Themachineitselfist hebrainlessbit,thecleverpartisthe program.Sohowdoyougoaboutwritingaprogram? It isn't asdifficultas you might think. The reason ist hat t here has been a great deal of progress in this r espect in the last twenty years. Many years ago computerswerebigmachineswhichhadtobeprogrammedbyskilled peoplewhounderstoodthenumbercodesystem- calledmachinecodethatthecomputerused.Asti mewenton,programmi nglanguageswere invented.Aprogramminglanguageisawayof instructing acomputer by usingcommandwordswhichareEnglishwords .Evenbeforemicrocomputersweredreamedof,therewereseveraloftheseprogramming languages,butthemost importantone forusisBASIC. BASIC isshort fo r BeginnersAll-purposeSymbolicInstruct ionCode.Itwasinventedat Dartmout hCollege,USA,asawayofteachingcomputerprogramming. Si nce then, ithasspread like wildfi re to become the programming language thatisusedforeachandeveryhomecomputer.It' sstillagoodlanguage forbeginnersint hesensethatit'seasytolearn,butithas alsodeveloped intoalanguagethatgivesyouagreatdealofcontroloveryour computer. YourcomputerusesaspecialvarietyofBASICwhichiscalledMSX BASIC.It'soneoft hemostuptodate varietiesof BASIC, andyetithas beendevel opedfr omoneoft hefirstversionsofBASICusedinsmall computers;MicrosoftBASIC.WhatthatallboilsdowntoisthatMSX BASlC iseasy t ouse, reliable, and yet capableof getting the best fr om your computer.UnliketheoldervarietiesofBASIC,t oo,itwi llworkonany MSXmachine.Canyouimagineaworldinwhichyourrecordswouldn' t playonyourneighbour' shi-fisystem?Wouldyoubuyacassette playerif youknewthatonlyonemake of cassettecouldbe usedwith it? That's the state thatcomput ing was inbefore MSX. Now for anyone who doesn't have an MSXmachine,that'st he wayitstillis,but for you, t hings are different. Your computercan use a tape or disk that was recorded by any other MSX computer.Anyone else whohasan MSX computer can make use of one of your tapes or disks. That's the way it should havebeen inthe first place, but it has taken MSX to do it.Hyou have never tu ned a TV receiver, or adjusted WhereDoWeStart?3 a cassette recorder, there's help for you in Appendices A and B at the end of thisbook. BASIC foundations TheBASI Clanguageisbuiltli keanyot herlanguage, with vocaculary and syntax.Vocabulary meanst hewordst hat are used to make t hings happen. Syntaxmeanst hewaythatyouhavetousethewords.Likeanyot her language,BASIChasruleswhichhavetobelearned.Whatmakesitso much easier for you to learn is that the words are mainly English words, and therulesare simple.Moreover, your computerwill tell youwhen you have disobeyedtherules! To learn about BASIC,then, youhave to learn what anumber of words mean.Thereareaboutonehundredofthesewords,andthemeaningof mostof themisobvious. In addition, you must learn the correct way to use eachword.Thisiswhere you really come up agai nst the 'brainless machine' bit.The computer canmake use of a command which usesthe correct word in t he correct way. If you use the wrong word, spell the word wrongly,or use it in thewrong way, t hemachine can' t do anyt hing - so it stops. When it does this, amessage will appear on t he screen to tell you what has happened. This iscalled an error-l1'zessage, and from what it says, you shouldbe able to fi nd whatwentwrong. If that makesit sound simple,that' s because it is simple, andthat's why it needstobelearned.Suppose,forexample,youhadaforeignfri endwho understoodonlyaboutonehundredwordsof English.Howwouldyou makehim understand,usi ng only the words he knows, that you want him to dosomet hingli kearrangewordsinalphabeticalorderorfindhowmany membersof the dominoesclub havepaid their subscripti ons? The answeris thatyouhavetobreakupthesecomplicat edact ionsintoalotof si mple steps.Yout henhave todescribeeach step in the words that your hundredword friend underst ands.There's one big difference here, though. Ahuman whoknowsahundredwordsof alanguagewillpickupot her wordsvery quickly.Acomputer does n't, so far,have thisability. Every ins truction has to be made out of these important command words, the keywords as we call them.Aprogramconsistsofanarrangementof thesekeywordsinsucha wayt hatsomet hi ngusefulisdone.Aprogrammightbeeducat ional, amusing,forbusinessorleisure,workingwi thwordsorwithnumbers; whatever you want itto be.Whateveritis,though, it st illhasto make use of t hesekeywords ,becausethat'sallthatthemachinecanunderstand.You can'ttypeinstructionslike'Whoorderedadozen spob-tackers?'or 'What willmypaymentsbeif Ipaybackonefifthof themortgage?' . Theseare questionsforhumanswithhumanbrains,notforcomputers.Computers havememory.Theycan store informationand t heycan store instructions. 4WorkingwithMSX BASIC They can't puzzleout what a newinstruction mightmean, though, which is whywehavetowrit eprograms. StructureofBASIC Oneof t hecommandwordsinBASI Cisusedheretoletyouseewhata BASIC programlooks like. The word is LIST, andyou useit by typing t he word,thenpressingthekeythatismarkedRETURNorENTER,or indicatedwithalargearrowwhichcurlsdownandleft.TheRETURN / ENTERkeyisanimportantone.It'sthe"doitnow'keythatmakesa commandwork. Why do we needit?Thebrainlessmachine,you see, can't tellwhenyou havefinishedtyping,and itneeds asignalto tellitthat what's thereiseverything- getonwi thit.TheRETURN / ENTERkeyprovides thatsignal.If youhaveaBASICprograminthe memory of the computer, thentypingLISTandpressingtheRETURN j ENTERkeywillmakethe program appear.Unless the program isvery short, it will t ake up much more spacethanisavailableonthescreen.Asnewinstructionsappearatthe bottomof thescreen,then,previousonesvanis h fromthe top. It' s j ust as if thescreenwasaframe,andt heprogramonalongsheetofpaperbeing woundthroughtheframe.Thisactioniscalledscrolling.Becauseof scroll ing, whatyou normally end up wit h when youuseLIST isthe last few setsofprograminstructions.Youcanstopt hescrolli ngatanystageby pressing theSTOP keyonce. Pressing STOPasecondtimewi llrestart the scrolling.If there is no program stored in t hememory of the computer, then usingLIST willproducenothi ng.Try itfor yourself byloadingone of t he sampleprogramsthatcamewithyourcomputer,andmakingitstopby pressi ngtheCTRL andSTOPkeystoget her.YoucannowusethisLI ST actiontoseewhatBASICcommandslooklike. Suppose,then, t hat you are looking at a program listing. What do you see onthescreen? The answerisasetof numberedlinesof instructionswhich use familiar looking words. These are linesof BASIC, and the numbering is there asaguidetot hecomputer.Normally,the computer wi llwork on the linesinorderofincreas ingnumber.Thisway,thelinenumbersshowin whichorderthe computermustcarryout t heinstruct ions.Another use for theselinenumbers,however,isbranching.You can include int heprogram instruct ionswhichforcethe machinetoworkonanotherline.Thisall ows theprogram tovary what themachine does.For example, you might want ittoprintfro malistof nameseachonewhosesubscri ptionisdue.This means sel ecting names, not just printing the wholelist.At some point in the program then,the machine willbe instructedto pri nt aname insteadof j ust moving ontothenextname. This is one type of branching action.Another one islooping.Looping means that the machine repeats a set of instructions, carryi ngthemoutoverandoveragai ninsteadofkeepingtothestrict numberorderofthelines.Thesetypesofactionareveryimportantin Where DoWeStart?5 computing,andinBASIC,thelinenumbersareusedinthecommands whichmaket hemachinecarrythemout.Thelinenumbers,then,arean essential part of BASIC. If you type anumber, the machine will always take t histobealinenumber. Youcan'tusethecomputerinthe way that you woulduseacalculator. Youcan' t,forexample,type: 26+ 42= asyouwouldwithacalculator,becausethecomputerisprogrammedto take 26asmea ni ng aline number.Since it is not programmed to do any sort of arithmeticwith linenumbers,itcan't make any sense of the +42 =t hat follows, soitissues the 'Syntaxerror'message inthe hope that you' llgetit rightnextti me.Onceyouunderstandthatthisisasimple-mindeddevice and not a pocket genius, you start to findthat programming becomesmuch easier! Oneotherthingt hatwillnotbotheryoumuchatthebeginningis memory.Thecomputerstoresallt heinstructionsforaprograminits memory;italsoneedstoreservesomememory for makingnotesasit goes along, and for organising the display on the TV screen.Memory is measured inunitsthatarecalledbytes.Onebyteistheamountof memorythatis neededtostoreoneinstructionword,oroneletterofanyotherwords. Becauseonebyteisasmallamountof memory,weusethewordkilobyte more often.One kilobyte (short enedtolK) is1024 bytesof memory.Many machines claim tohave 64K of memory, and they do, but only a part ofthis canbeusedby you.Normally,if your machinereleases28Kor so for you, t here willbe enough memory for any program that you are li kely to write for yourself. Summi ngitupsofar,then,programmingmeanswritinginstructions which are broken down into simple steps.These steps make use of a limited numberof keywords,whichmustbeusedinthecorrect way and wit h the correct spelling.The keywordsare,inturn, arrangedinnumbered lines, so thatthe computercan carry out t he instructions in the correct order. From allthis,you' llsee t hattyping isan important part of all this activity, and so we' lllooknextatthekeyboardonwhichyouhavetotypeallofthese keywordsandtheotherpartsof inst ructions. The keyboard Sincethekeyboardisthewaythat weenter the instructionsof aprogram into the computer, we need to take a close look at this vital component. Now justbecause all of the MSX machines will run the same programs and can be programmedinthe same way,that doesn't mean that all the keyboards will bealike. Some machines willuse good-quality keyboards with moving keys as you would expect in atypewriter.Others may use the flat-pad keys, or the 4WorkingwithMSX BASIC They can't puzzleout what a newinstruction mightmean, though, which is whywehavetowrit eprograms. StructureofBASIC Oneof t hecommandwordsinBASI Cisusedheretoletyouseewhata BASIC programlooks like. The word is LIST, andyou useit by typing t he word,thenpressingthekeythatismarkedRETURNorENTER,or indicatedwithalargearrowwhichcurlsdownandleft.TheRETURN / ENTERkeyisanimportantone.It'sthe"doitnow'keythatmakesa commandwork. Why do we needit?Thebrainlessmachine,you see, can't tellwhenyou havefinishedtyping,and itneeds asignalto tellitthat what's thereiseverything- getonwi thit.TheRETURN / ENTERkeyprovides thatsignal.If youhaveaBASICprograminthe memory of the computer, thentypingLISTandpressingtheRETURN j ENTERkeywillmakethe program appear.Unless the program isvery short, it will t ake up much more spacethanisavailableonthescreen.Asnewinstructionsappearatthe bottomof thescreen,then,previousonesvanis h fromthe top. It' s j ust as if thescreenwasaframe,andt heprogramonalongsheetofpaperbeing woundthroughtheframe.Thisactioniscalledscrolling.Becauseof scroll ing, whatyou normally end up wit h when youuseLIST isthe last few setsofprograminstructions.Youcanstopt hescrolli ngatanystageby pressing theSTOP keyonce. Pressing STOPasecondtimewi llrestart the scrolling.If there is no program stored in t hememory of the computer, then usingLIST willproducenothi ng.Try itfor yourself byloadingone of t he sampleprogramsthatcamewithyourcomputer,andmakingitstopby pressi ngtheCTRL andSTOPkeystoget her.YoucannowusethisLI ST actiontoseewhatBASICcommandslooklike. Suppose,then, t hat you are looking at a program listing. What do you see onthescreen? The answerisasetof numberedlinesof instructionswhich use familiar looking words. These are linesof BASIC, and the numbering is there asaguidetot hecomputer.Normally,the computer wi llwork on the linesinorderofincreas ingnumber.Thisway,thelinenumbersshowin whichorderthe computermustcarryout t heinstruct ions.Another use for theselinenumbers,however,isbranching.You can include int heprogram instruct ionswhichforcethe machinetoworkonanotherline.Thisall ows theprogram tovary what themachine does.For example, you might want ittoprintfro malistof nameseachonewhosesubscri ptionisdue.This means sel ecting names, not just printing the wholelist.At some point in the program then,the machine willbe instructedto pri nt aname insteadof j ust moving ontothenextname. This is one type of branching action.Another one islooping.Looping means that the machine repeats a set of instructions, carryi ngthemoutoverandoveragai ninsteadofkeepingtothestrict numberorderofthelines.Thesetypesofactionareveryimportantin Where DoWeStart?5 computing,andinBASIC,thelinenumbersareusedinthecommands whichmaket hemachinecarrythemout.Thelinenumbers,then,arean essential part of BASIC. If you type anumber, the machine will always take t histobealinenumber. Youcan'tusethecomputerinthe way that you woulduseacalculator. Youcan' t,forexample,type: 26+ 42= asyouwouldwithacalculator,becausethecomputerisprogrammedto take 26asmea ni ng aline number.Since it is not programmed to do any sort of arithmeticwith linenumbers,itcan't make any sense of the +42 =t hat follows, soitissues the 'Syntaxerror'message inthe hope that you' llgetit rightnextti me.Onceyouunderstandthatthisisasimple-mindeddevice and not a pocket genius, you start to findthat programming becomesmuch easier! Oneotherthingt hatwillnotbotheryoumuchatthebeginningis memory.Thecomputerstoresallt heinstructionsforaprograminits memory;italsoneedstoreservesomememory for makingnotesasit goes along, and for organising the display on the TV screen.Memory is measured inunitsthatarecalledbytes.Onebyteistheamountof memorythatis neededtostoreoneinstructionword,oroneletterofanyotherwords. Becauseonebyteisasmallamountof memory,weusethewordkilobyte more often.One kilobyte (short enedtolK) is1024 bytesof memory.Many machines claim tohave 64K of memory, and they do, but only a part ofthis canbeusedby you.Normally,if your machinereleases28Kor so for you, t here willbe enough memory for any program that you are li kely to write for yourself. Summi ngitupsofar,then,programmingmeanswritinginstructions which are broken down into simple steps.These steps make use of a limited numberof keywords,whichmustbeusedinthecorrect way and wit h the correct spelling.The keywordsare,inturn, arrangedinnumbered lines, so thatthe computercan carry out t he instructions in the correct order. From allthis,you' llsee t hattyping isan important part of all this activity, and so we' lllooknextatthekeyboardonwhichyouhavetotypeallofthese keywordsandtheotherpartsof inst ructions. The keyboard Sincethekeyboardisthewaythat weenter the instructionsof aprogram into the computer, we need to take a close look at this vital component. Now justbecause all of the MSX machines will run the same programs and can be programmedinthe same way,that doesn't mean that all the keyboards will bealike. Some machines willuse good-quality keyboards with moving keys as you would expect in atypewriter.Others may use the flat-pad keys, or the 6WorkingwithMSX BASIC calculator-style keys that can save the manufacturer so much money. If you are going to do alotofprogramming, or if you intend to use the computer foranything other than games, a good keyboardis essential.More working computers are thrown away because of poor keyboardsthan for any other reason,andif,likeme,youspendalotof timeatthekeyboard,you'll understandwhy.Whenyoubegincomputing,youmaythinkthatt he keyboard doesn't matter, but as you move on, you can soon be reminded of howimportantagoodkeyboardis. When you have the computer ready forprogramming, you will see on the screenamarker whichiscalled the cursor.On most machines , this marker draws attention to itself by flashing.When you press a key which islabelled with aletterornumber or anything elsethat can beprinted, then the place where it will appear on the screen is marked by this cursor. If you press the A key, for example, you will see the letter a or A appear where the cursor was, and the cursor will move one space to the right. When the cursor gets to the right-handsideof the screen, youdon't have todo anything different. J ust pressthenextletterthatyouwant,andyouwillsee t heletter appear;the cursor willmove to the start of the next line, at the left-hand side. You do not have topress the RETURNor ENTER key to make this cursor movement happen.Note that t hebottom lineof the screenshows the setof keywords that canbe obtained simply by pressing one of the Fkeys on the top row of the keyboard.Another set of words appears when you press the SHIFT key, and this shows what can be entered when the Fkeys are used along with the SHIFTkey. The style of keyboard can vary, and so also can the keys that you findon it.The main keys, which give the letters,numbers, and punctuation marks, are the same on allMSX keyboards. On many machines, these keys are in a lightercolourthantheotherkeys.Whatcanbedifferent,however,ist he otherkeysthat surround these, and so we'll look at the other keys first.The mostimportantoneisthekeywhichonsomecomputersismarked RETURN,andonothersismarkedENTER.Afewcomputersusea symbol,whichisathick arrow that curls downwards and left.It's the same key,doingthesamejob,andisinthesameplaceonanykeyboard.It's placedsothat youcanhititwith thelittlefingerof yourright hand. The effect of this keyis,as you know already, to signal to the computer that you have finished a command or a reply or a program line, and you now want the machinetodosomethingaboutit.ThewordENTERisfoundonsome keyboards because this key will enterwhat you have typed into the memory. The wordRETURN isusedon othersbecause thekeyisin the position of thecarriagereturnkeyof atypewriter.Eitherway,ithelpsif thiskeyis biggerthantheothers,providing itdoesn't jamifyouhit itoff-centre. After theRETURN jENTER key, we can look at t he others in any order welike,andthe easiestwayis to look firstat the top row of keys - the row which contains asetof five keys that are marked withFI,F2 . . . up to FlO. Thesearecalled the programmable functionkeys, and the idea isthat you WhereDoWeStart?7 uset hemtosaveyourselftyping.Forexample,whenyouare enteringa program, you may findthat you have to use a keyword, or a combination of keywords,overandoveragain.Eachofthesespecialkeyscanbe programmedto do thiswork, so that youneedtype the word(s) once only. From thenon,you use theprogrammable functionkeys for the words that you have programmed into them.For example, if you findthat you needto keep using the word PRINT, then you couldprogram this into FlO, and hit FlOeachti meyouwantedthe wordPRINT t oappear on thescreen.The wordst hat areassignedto thesekeyswillappear onthebottom lineof t he screen,aswe'venotedalready.There'smoreaboutthisinChapter12. Stayi ngonthetoprow,andmovingacr osstotheright,you'llfindthe STOPkey.Thisisanimportantkeywhenyouarerunning aprogram,or trying tomakeone run.Pressing thiskeyonce willmake the machine stop runningthep r o g r a m ~pressingitasecondtimewi llallowthemachineto continue.Unlikesomecomputers,theMSXmachinescancontin uejust where t heyleftoff when you press this STOP key for the second ti me. It's a verygoodway of givingyoutime totakeaclose lookatsomethingon the screen, for example,without forcing you to start the program allover again tofindoutwhathappensnext. Nowthisiswheredifferentmanufacturershavedifferentideasabout where keysshoul dbe placed. To t heright of the STOP key, you should find agroupof t hreeor fourediting keys.Asthename suggests,these are the keysthatyouwillusewhenyouwanttocorrectsomethi ngthathasgone wrong inaprogram. Some manufacturers put these keys on the top line and someputtheminagroupontheri ght-handside,nearthetop.Theyare oftenmarkedasINS,DELandHOME.INSmeansINSertletters,and DEL means DELete letters.HOME means that you want to beable to type letterswhichwillbeplacedstartingatthetopleft-handsideofablank screen.TherearemoredetailsaboutusingthesekeysalsoinChapter12. Anotherkeywhich is useful for correcting mi stakesis the backspace key. ItismarkedBSbysomemanufacturersorlabelledwi thaleft-point ing arrowbyot hers. If you press this key the cursor wi llmove one spacelefton t he screen, and willwipe out the letter that wasin t hat place. It's a quick and easywayofcorrect ingamistakewhenyouhavejustnoticedit,before pressing theRETURNor ENTER key.On some machinesyou can get the cursort omoveintheoppositedirection,lefttoright,wit hakeythatis markedTAB.Onothermachinesthiskeyismarkedwithari ght-pointing arrow.Thiskeyisplacedontheleft-handsideof thekeyboard . Twoother keys on the left-hand side are labelledESC (or ESCAPE) and CTRL (or CONTROL).Whenyou firststart to learn about programming, you won't have muchusefor thesekeys,and I'llexplain them aswego on. All of the MSX computers al so usetwo SHIFT keys,one on each side ofthe bottom row of letter keys.Thesework in the same way as the SHIFT keys of a typewrit er.When you switch on the machine ready to use, pressing a letter keygivessmallletters,thetypewhichwecalllower-case.Togetcapital 6WorkingwithMSX BASIC calculator-style keys that can save the manufacturer so much money. If you are going to do alotofprogramming, or if you intend to use the computer foranything other than games, a good keyboardis essential.More working computers are thrown away because of poor keyboardsthan for any other reason,andif,likeme,youspendalotof timeatthekeyboard,you'll understandwhy.Whenyoubegincomputing,youmaythinkthatt he keyboard doesn't matter, but as you move on, you can soon be reminded of howimportantagoodkeyboardis. When you have the computer ready forprogramming, you will see on the screenamarker whichiscalled the cursor.On most machines , this marker draws attention to itself by flashing.When you press a key which islabelled with aletterornumber or anything elsethat can beprinted, then the place where it will appear on the screen is marked by this cursor. If you press the A key, for example, you will see the letter a or A appear where the cursor was, and the cursor will move one space to the right. When the cursor gets to the right-handsideof the screen, youdon't have todo anything different. J ust pressthenextletterthatyouwant,andyouwillsee t heletter appear;the cursor willmove to the start of the next line, at the left-hand side. You do not have topress the RETURNor ENTER key to make this cursor movement happen.Note that t hebottom lineof the screenshows the setof keywords that canbe obtained simply by pressing one of the Fkeys on the top row of the keyboard.Another set of words appears when you press the SHIFT key, and this shows what can be entered when the Fkeys are used along with the SHIFTkey. The style of keyboard can vary, and so also can the keys that you findon it.The main keys, which give the letters,numbers, and punctuation marks, are the same on allMSX keyboards. On many machines, these keys are in a lightercolourthantheotherkeys.Whatcanbedifferent,however,ist he otherkeysthat surround these, and so we'll look at the other keys first.The mostimportantoneisthekeywhichonsomecomputersismarked RETURN,andonothersismarkedENTER.Afewcomputersusea symbol,whichisathick arrow that curls downwards and left.It's the same key,doingthesamejob,andisinthesameplaceonanykeyboard.It's placedsothat youcanhititwith thelittlefingerof yourright hand. The effect of this keyis,as you know already, to signal to the computer that you have finished a command or a reply or a program line, and you now want the machinetodosomethingaboutit.ThewordENTERisfoundonsome keyboards because this key will enterwhat you have typed into the memory. The wordRETURN isusedon othersbecause thekeyisin the position of thecarriagereturnkeyof atypewriter.Eitherway,ithelpsif thiskeyis biggerthantheothers,providing itdoesn't jamifyouhit itoff-centre. After theRETURN jENTER key, we can look at t he others in any order welike,andthe easiestwayis to look firstat the top row of keys - the row which contains asetof five keys that are marked withFI,F2 . . . up to FlO. Thesearecalled the programmable functionkeys, and the idea isthat you WhereDoWeStart?7 uset hemtosaveyourselftyping.Forexample,whenyouare enteringa program, you may findthat you have to use a keyword, or a combination of keywords,overandoveragain.Eachofthesespecialkeyscanbe programmedto do thiswork, so that youneedtype the word(s) once only. From thenon,you use theprogrammable functionkeys for the words that you have programmed into them.For example, if you findthat you needto keep using the word PRINT, then you couldprogram this into FlO, and hit FlOeachti meyouwantedthe wordPRINT t oappear on thescreen.The wordst hat areassignedto thesekeyswillappear onthebottom lineof t he screen,aswe'venotedalready.There'smoreaboutthisinChapter12. Stayi ngonthetoprow,andmovingacr osstotheright,you'llfindthe STOPkey.Thisisanimportantkeywhenyouarerunning aprogram,or trying tomakeone run.Pressing thiskeyonce willmake the machine stop runningthep r o g r a m ~pressingitasecondtimewi llallowthemachineto continue.Unlikesomecomputers,theMSXmachinescancontin uejust where t heyleftoff when you press this STOP key for the second ti me. It's a verygoodway of givingyoutime totakeaclose lookatsomethingon the screen, for example,without forcing you to start the program allover again tofindoutwhathappensnext. Nowthisiswheredifferentmanufacturershavedifferentideasabout where keysshoul dbe placed. To t heright of the STOP key, you should find agroupof t hreeor fourediting keys.Asthename suggests,these are the keysthatyouwillusewhenyouwanttocorrectsomethi ngthathasgone wrong inaprogram. Some manufacturers put these keys on the top line and someputtheminagroupontheri ght-handside,nearthetop.Theyare oftenmarkedasINS,DELandHOME.INSmeansINSertletters,and DEL means DELete letters.HOME means that you want to beable to type letterswhichwillbeplacedstartingatthetopleft-handsideofablank screen.TherearemoredetailsaboutusingthesekeysalsoinChapter12. Anotherkeywhich is useful for correcting mi stakesis the backspace key. ItismarkedBSbysomemanufacturersorlabelledwi thaleft-point ing arrowbyot hers. If you press this key the cursor wi llmove one spacelefton t he screen, and willwipe out the letter that wasin t hat place. It's a quick and easywayofcorrect ingamistakewhenyouhavejustnoticedit,before pressing theRETURNor ENTER key.On some machinesyou can get the cursort omoveintheoppositedirection,lefttoright,wit hakeythatis markedTAB.Onothermachinesthiskeyismarkedwithari ght-pointing arrow.Thiskeyisplacedontheleft-handsideof thekeyboard . Twoother keys on the left-hand side are labelledESC (or ESCAPE) and CTRL (or CONTROL).Whenyou firststart to learn about programming, you won't have muchusefor thesekeys,and I'llexplain them aswego on. All of the MSX computers al so usetwo SHIFT keys,one on each side ofthe bottom row of letter keys.Thesework in the same way as the SHIFT keys of a typewrit er.When you switch on the machine ready to use, pressing a letter keygivessmallletters,thetypewhichwecalllower-case.Togetcapital 8 9 WorkingwithMSX BASIC letters,or upper-case,youneedtopressaSHIFT key al ong with the letter key.Eit herSHIFTkeywilldo,andtheyareplacedsothatyoushould alwayshaveaspare fingertopressoneof them. Afterthat,it'severymanufacturerforhimself.Somemachineshavea group of keys on the right-hand side,marked with arrows.These are cursor controlkeys,andtheir effectistomove the cursorup,down, leftor right, accordingtowhichkeyyoupress.Notallkeyboardsgroupthesekeys neatly,andyoujusthavetofindthemforyourownparticularmachine. Finally,t here willbe some keys on the same bottom line of the keyboard as thelongspacebarkey.TheusualgroupisCAPS,GRAPHandCODE. SomemachineslabeltheCAPSkeyasCAPSSHIFT.It'sveryusefulif thereisalightnearthiskeywhichcomesonwhenthemachineissetfor capitals.Whateverithappenstobelabelled,itseffectistoswitchcapital letterson or off.If, asyou type, you see lower-case (small) letters appear on the screen,thenpressing CAPS or CAPS SHIFT once will make all of your typedletters appear in upper-case (capital) letters. You will still have to press the SHIFT key,however,if youwantt hesymbols whichare shown on the upper partof the number keys, and some of the keyson theright- hand side of the keyboard. Pressing the CAPS or CAPS LOCK key a second time will getyoubacktolower-caselettersagain. TheCODEandGRAPHkeysarelessimportantwhenyoustart programming.Theyare usedlikethe shift key,but their effect is to provide youwithacompletelydifferentsetof lettersandshapes. The CODE key, whichcanbeusedal ongwit htheSHIFTkey,providesyouwithletters forotherEuropeanlanguages,andasetofmathematicalsymbols,as youpressthekeys.Usi ngtheGRAPHkey,withor withoutSHIFT, gives graphicalsymbolsandsomemoremat hematical symbols.Thesesymbols andlettersshouldbeillustratedinthemanualwhichcomeswit hyour computer. Interpretingandcompiling ComputinglanguageslikeBAS1Ccanbearrangedintwoways.Oneof these ways iscalled interpreted and the other compiled. The BASIC in your MSXcomputer isinterpreted.Thismeansthattheinstructionswhich you type are held in the memoryof the computer as a set of code numbers. When yourunaprogram,eachcodenumberforaninstructionhastobe interpreted. Thismeans that themachine hastofindwhat the code means and then act on it.Acting on it means that the machine has to locate another setof codesinitsmemory,anduse these todi rectthemicroprocessor,the Z-80,whichisatt heheartofthecomputer.Alanguagewhichuses interpretationisslow,because each command has t o belooked up,in turn, asthecomputercomestoit.A compiler,bycontrast, doesthelookingup justonceaftertheprogramhasbeenwritten.Theinstructionsarethen WhereDoWeStart? turneddi rectlyintothemicroprocessorcodes . When acompiledprogram runs,t hen,thereisnolookinguptodo,andthespeedcan be verymuch fas ter. The language that you are provided with isinterpreted BASIC, but if your MSXcomputerhasenoughmemory,itispossi bletoinsertacartri dge whichwillprovide youwith a compiled language. This language willbe yet somet hingelsetoJearn,soyoumaynotwanttothinkaboutitatthe moment.Astime goes on, though, you may feel that you need to use a fasterrunning language. The great advantage of an MSX computer is that you have thechoice. 8 9 WorkingwithMSX BASIC letters,or upper-case,youneedtopressaSHIFT key al ong with the letter key.Eit herSHIFTkeywilldo,andtheyareplacedsothatyoushould alwayshaveaspare fingertopressoneof them. Afterthat,it'severymanufacturerforhimself.Somemachineshavea group of keys on the right-hand side,marked with arrows.These are cursor controlkeys,andtheir effectistomove the cursorup,down, leftor right, accordingtowhichkeyyoupress.Notallkeyboardsgroupthesekeys neatly,andyoujusthavetofindthemforyourownparticularmachine. Finally,t here willbe some keys on the same bottom line of the keyboard as thelongspacebarkey.TheusualgroupisCAPS,GRAPHandCODE. SomemachineslabeltheCAPSkeyasCAPSSHIFT.It'sveryusefulif thereisalightnearthiskeywhichcomesonwhenthemachineissetfor capitals.Whateverithappenstobelabelled,itseffectistoswitchcapital letterson or off.If, asyou type, you see lower-case (small) letters appear on the screen,thenpressing CAPS or CAPS SHIFT once will make all of your typedletters appear in upper-case (capital) letters. You will still have to press the SHIFT key,however,if youwantt hesymbols whichare shown on the upper partof the number keys, and some of the keyson theright- hand side of the keyboard. Pressing the CAPS or CAPS LOCK key a second time will getyoubacktolower-caselettersagain. TheCODEandGRAPHkeysarelessimportantwhenyoustart programming.Theyare usedlikethe shift key,but their effect is to provide youwithacompletelydifferentsetof lettersandshapes. The CODE key, whichcanbeusedal ongwit htheSHIFTkey,providesyouwithletters forotherEuropeanlanguages,andasetofmathematicalsymbols,as youpressthekeys.Usi ngtheGRAPHkey,withor withoutSHIFT, gives graphicalsymbolsandsomemoremat hematical symbols.Thesesymbols andlettersshouldbeillustratedinthemanualwhichcomeswit hyour computer. Interpretingandcompiling ComputinglanguageslikeBAS1Ccanbearrangedintwoways.Oneof these ways iscalled interpreted and the other compiled. The BASIC in your MSXcomputer isinterpreted.Thismeansthattheinstructionswhich you type are held in the memoryof the computer as a set of code numbers. When yourunaprogram,eachcodenumberforaninstructionhastobe interpreted. Thismeans that themachine hastofindwhat the code means and then act on it.Acting on it means that the machine has to locate another setof codesinitsmemory,anduse these todi rectthemicroprocessor,the Z-80,whichisatt heheartofthecomputer.Alanguagewhichuses interpretationisslow,because each command has t o belooked up,in turn, asthecomputercomestoit.A compiler,bycontrast, doesthelookingup justonceaftertheprogramhasbeenwritten.Theinstructionsarethen WhereDoWeStart? turneddi rectlyintothemicroprocessorcodes . When acompiledprogram runs,t hen,thereisnolookinguptodo,andthespeedcan be verymuch fas ter. The language that you are provided with isinterpreted BASIC, but if your MSXcomputerhasenoughmemory,itispossi bletoinsertacartri dge whichwillprovide youwith a compiled language. This language willbe yet somet hingelsetoJearn,soyoumaynotwanttothinkaboutitatthe moment.Astime goes on, though, you may feel that you need to use a fasterrunning language. The great advantage of an MSX computer is that you have thechoice. Chapter Two nputs and Outputs Chapter1 will havebrokenyouinto the idea t hat the MSX computer, li ke practically allcomputers, takes its orders fr om you when you type them on thekeyboard. Youwillalsohavefoundthat anorderis obeyedwhen the RETURN orENTERkeyispressed.From now on,we'll use j ust the word RETURN to mean eit her of t hese, whatever the key happens to be labelled on the keyboard. You willalso know that you can use the command LIST (t hen pressRETURN)toprintyourprograminstruct ionsonthescreen. Therearet woot herusefulpointst hatyouneedtoknowbeforewego much fu rt her.One is t hat you canclear the screen by pressing t he key that is markedHOME at t he same time asthe SHIFT key. This also has the effect of placing the cursor at the top left -hand corner of t he screen. The messages atthebottomof t hescreenarenOTerasedinthisway,however.You can obtaint he same screen clearing effect by pressing the CTRL key along with t he Lkey.Pressing CTRL andLtogetherisusualJ y wri ttenasCTRL L to savespace.As yourfamili aritywit hthe computerkeyboardincreases, you willwant t omake useof the editingcommands,and t hese are explained in Chapter12. Now there aretwowaysinwhichyoucan use acomputer.One iscalled direct mode. Di rect mode means that you type a command, pressRETU R N, andthecommandiscarriedoutat once.Thiscanbe useful,but themore importantwayof usingacomputeris inwhatiscalled programmode. In thismode t hecomputerisissuedwithasetofinst ructi ons, withaguide to the order inwhich t hey are to be carriedout.A set of instructions like t his is calleda program.The difference isimportant,because t he instructions of a programcanberepeated asmany timesasyou li ke wit h very little effort on your part.Adirectcommand, bycontrast, willbe repeated only if you type thewholecommandagai nandt henpressRETURN.Thesetof command words that canbe used, along with therules for using them, make up what is call eda programminglanguage, which for your computer isMSX BASIC. Let'snowtake alook at thedifferencebetweenadirectcommand and a programinstruction.If youwantthecomputertocarryoutthedi rect commandtoaddtwonumbers,say1. 6and3.2,thenyouhavet otype: print1.6+ 3.2(andthenpressRETURN) Inputs and Outputs11 Youhavetostartwit hprint(orPRINT)oritsabbreviation?becausea co mputerisa dumb machine and itobeys only a few set instructions.Unless youusethewordprint,thecomputer hasno wayof telling that what you want isto see the answer on the screen. It doesn't recognise instructions like GIVEMEorWHAT IS; onlyafewwords (about ahundredandfortyof them)that wecall itsreserved words or instruct ionwords. PRINT is one of these words.So thatyoucanrecognisethese reservedwords more easily in thisbook t heywillappearinupper-case (capital) letters fromnow on.You knowbynow,however,thatyoucantypethemineitherupper-caseor lower-case.Youwillalwaysseetheminupper-casewhenyouLISTyour program. Whenyoupresst heRETURNkeyaftertypingPRINT1. 6+ 3. 2,the screenshowstheanswer,4.8,underthecommand.Thisanswerisnot printedat the extreme left-hand sideof thescreen;it' splacedone space in, andthewordO.kappearsundert hisanswer.TheO.k.isaprompt- a remindert hatt hecomputerisreadyforanothercommand.Oncethi s commandhasbeencarriedout,however,it'sfinished. Aprogram does not work inthe same way.A program is typed in, but t he instructionsoft heprogramarenotcarriedoutwhenyoupressthe RETURNkey.I nstead,theinstructions are stored in the memory, ready to becarriedoutasandwhenyouwant.Thecomputerneedssomewayof recognisingthedifferencebetweenyourcommandsandyourprogram instructions,however.OncomputersthatuseBASICthisisdoneby startingeachprogramins t ructionswit hanum berwhichiscalledaline number.Thismustbe apositive whole number - the type of number thatis calledapositiveint eger.WelookedatthisideabrieflyinChapterI. ThePRINTinstruction,then,isthewayt hatwegetthecomputerto provideuswit hinformation.Apartfromsomegamesprograms,most computerusesinvolve t hree thi ngs; inputs, processes, and outputs. The hard partaboutprogrammingisnotlearningthelanguageofBASIC;it' s learninghowtogetwhatyouwantfromtheset hreeactions.Forthe moment,we'llleaveinputsasideandconcentrateonoutputsandalittle processing. Processing means doing whatever we want t o do with numbers or words. Itcanbe assimpleasadding two numbers, or as complicated as putting a set ofnamesandaddressesintoal phabeticalorderof surname.It canmean producing shapes and colours on t he screen andmoving them about.It can meanproducing sound, eit hersoundeffectsor music, to go with the screen displays. Summing it all up,it means all of the actions that make a computer sointeresting andsouseful. Let' sstartprogramming,then,withthearithmeticactionsofadd, subt ract ,multiplyanddivide.Computersaren'tusedverymuchfor / calculation,but it' s useful to be able to carry out calculations now and again. Inaddition, youaremuchmore li kelytorecognisethe sortof inst ructions that usenumberst hantheoneswhichare used to work with words. F igure Chapter Two nputs and Outputs Chapter1 will havebrokenyouinto the idea t hat the MSX computer, li ke practically allcomputers, takes its orders fr om you when you type them on thekeyboard. Youwillalsohavefoundthat anorderis obeyedwhen the RETURN orENTERkeyispressed.From now on,we'll use j ust the word RETURN to mean eit her of t hese, whatever the key happens to be labelled on the keyboard. You willalso know that you can use the command LIST (t hen pressRETURN)toprintyourprograminstruct ionsonthescreen. Therearet woot herusefulpointst hatyouneedtoknowbeforewego much fu rt her.One is t hat you canclear the screen by pressing t he key that is markedHOME at t he same time asthe SHIFT key. This also has the effect of placing the cursor at the top left -hand corner of t he screen. The messages atthebottomof t hescreenarenOTerasedinthisway,however.You can obtaint he same screen clearing effect by pressing the CTRL key along with t he Lkey.Pressing CTRL andLtogetherisusualJ y wri ttenasCTRL L to savespace.As yourfamili aritywit hthe computerkeyboardincreases, you willwant t omake useof the editingcommands,and t hese are explained in Chapter12. Now there aretwowaysinwhichyoucan use acomputer.One iscalled direct mode. Di rect mode means that you type a command, pressRETU R N, andthecommandiscarriedoutat once.Thiscanbe useful,but themore importantwayof usingacomputeris inwhatiscalled programmode. In thismode t hecomputerisissuedwithasetofinst ructi ons, withaguide to the order inwhich t hey are to be carriedout.A set of instructions like t his is calleda program.The difference isimportant,because t he instructions of a programcanberepeated asmany timesasyou li ke wit h very little effort on your part.Adirectcommand, bycontrast, willbe repeated only if you type thewholecommandagai nandt henpressRETURN.Thesetof command words that canbe used, along with therules for using them, make up what is call eda programminglanguage, which for your computer isMSX BASIC. Let'snowtake alook at thedifferencebetweenadirectcommand and a programinstruction.If youwantthecomputertocarryoutthedi rect commandtoaddtwonumbers,say1. 6and3.2,thenyouhavet otype: print1.6+ 3.2(andthenpressRETURN) Inputs and Outputs11 Youhavetostartwit hprint(orPRINT)oritsabbreviation?becausea co mputerisa dumb machine and itobeys only a few set instructions.Unless youusethewordprint,thecomputer hasno wayof telling that what you want isto see the answer on the screen. It doesn't recognise instructions like GIVEMEorWHAT IS; onlyafewwords (about ahundredandfortyof them)that wecall itsreserved words or instruct ionwords. PRINT is one of these words.So thatyoucanrecognisethese reservedwords more easily in thisbook t heywillappearinupper-case (capital) letters fromnow on.You knowbynow,however,thatyoucantypethemineitherupper-caseor lower-case.Youwillalwaysseetheminupper-casewhenyouLISTyour program. Whenyoupresst heRETURNkeyaftertypingPRINT1. 6+ 3. 2,the screenshowstheanswer,4.8,underthecommand.Thisanswerisnot printedat the extreme left-hand sideof thescreen;it' splacedone space in, andthewordO.kappearsundert hisanswer.TheO.k.isaprompt- a remindert hatt hecomputerisreadyforanothercommand.Oncethi s commandhasbeencarriedout,however,it'sfinished. Aprogram does not work inthe same way.A program is typed in, but t he instructionsoft heprogramarenotcarriedoutwhenyoupressthe RETURNkey.I nstead,theinstructions are stored in the memory, ready to becarriedoutasandwhenyouwant.Thecomputerneedssomewayof recognisingthedifferencebetweenyourcommandsandyourprogram instructions,however.OncomputersthatuseBASICthisisdoneby startingeachprogramins t ructionswit hanum berwhichiscalledaline number.Thismustbe apositive whole number - the type of number thatis calledapositiveint eger.WelookedatthisideabrieflyinChapterI. ThePRINTinstruction,then,isthewayt hatwegetthecomputerto provideuswit hinformation.Apartfromsomegamesprograms,most computerusesinvolve t hree thi ngs; inputs, processes, and outputs. The hard partaboutprogrammingisnotlearningthelanguageofBASIC;it' s learninghowtogetwhatyouwantfromtheset hreeactions.Forthe moment,we'llleaveinputsasideandconcentrateonoutputsandalittle processing. Processing means doing whatever we want t o do with numbers or words. Itcanbe assimpleasadding two numbers, or as complicated as putting a set ofnamesandaddressesintoal phabeticalorderof surname.It canmean producing shapes and colours on t he screen andmoving them about.It can meanproducing sound, eit hersoundeffectsor music, to go with the screen displays. Summing it all up,it means all of the actions that make a computer sointeresting andsouseful. Let' sstartprogramming,then,withthearithmeticactionsofadd, subt ract ,multiplyanddivide.Computersaren'tusedverymuchfor / calculation,but it' s useful to be able to carry out calculations now and again. Inaddition, youaremuchmore li kelytorecognisethe sortof inst ructions that usenumberst hantheoneswhichare used to work with words. F igure 12WorkingwithMSX BASIC 2. 1 shows afour line program which willprint some arithmetic results. The processhereconsistsof fouritemsof arithmetic,eachwithanoutput. 10PRINT5.6+6.8 2 ~ 'PRINT9.2-4.7 30PRINT3. 3*3.9 40PRINT7.6/1.4 Fig. 2. 1. Af ourlineari th meticprogram. Take aclose look at thisbecause there's a lot toget used to in these four lines.To start with, the line numbers are 10,20,30, 40 rather t han 1, 2, 3,4. Thisistoallowspaceforsecondt houghts. If you decidethat youwantto haveanother inst ructionbetweenline10and line 20, then you can type the linenumber15,or11or12or any ot her whole number between 10and 20, andfollowitwit h your new instruction. Even though you have entered this line outof order, the computerwillautomatically place it in orderbetween lines10and20.If younum beryourlines1,2, 3,thenthere'snoroomfor these secondthoughts,thoughyoucanchangelinenumbers if you have to byusing the editing commands. Thisidea of havi ng line numbers that go in tensissocommonthatit' sbuiltintoyourMSXcomputer.If youtype AUTO,orpresstheF2key,andthenpressRETURN,youwillseethe number10appearonthe screen.Youcanthentypet hefirstlineof your program. Whenyou press the RETURN keyat the endof t his first line, the nextli nenumberisautomaticallyselectedforyou.If youhavealineof programwi tht hisnumberalready,anasteriskappearsagainsttheline number.ThisC\.utomaticnumberi ngsystemcansaveyoualotof typing! The nextthing tonotice ishow the numberzeroonthe screen is slashed across.Thisistodist inguishitfromtheletterO.Thecomputersimply won't acceptthe 0inplaceof 0, nor t he 0in place of 0;the slashing makes thisdifferencemoreobvioustoyou,sothatyouarelesslikelytomake mistakes.Thezerothatyouseeon thekeyboardmaybeslashedor not, depending onthe manufacturerof the machine,butitison adifferent key from the 0and is differently shaped.Type some zeros and Os on the screen sothat youcanseethedifference. N ow to more important points. The star or asterisk symbol in line 30 is the symbol t hat the MSX computer uses as a multiply sign. Once again, we can't use the Xthat you might normally use for writing mUltiplication because X isaletter.There'snodividesignonthekeyboardeither,sotheMSX computer, like allother small computers, uses/, the slash sign,in its place. Thisisthe diagonal line which is on the same key as the question mark, not theonewhichslopestheotherwayandisinadifferentplace ondifferent MSXcomputers. So far, so good. The program is entered by typing it just as you see it.You don't needt o leave any space between the line number and the Pof PRINT Inputsand Outputs13 becauset heMSXcomputerwillputoneinforyouwhenitdisplaysthe programont hescreen. Youdon'tneedto leaveaspacefollowing PRINT eit her,andyoucantype?inplaceofPRINTifyouwish.TheMSX computer is very tolerant about this sort of t hing, so don't be surprised when youseeaprogramlistinginthisbookwhichshowswordsruntogether. There are some places where you must leavespaces, however, and we'll deal wit ht heseaswecometothem.Rememberthatyouhaveonlyalimited numberofbytesof memoryavai lable,andeachspaceusesoneof these bytes.Later on, asyoubecome accustomedtoprogrammi ng,you willfind t hatyouneedallthememoryyoucanget.You' llbegl adifyourMSX computer alreadyhas around28000bytesavailable, orallows lots of extra memorytobeadded. Gettingbacktotheprogramexample,youwillhavetopresst he RETURNkeywhenyouhavecompletedeachinstructionlinebefore you type t he next line number.You should end up wi th t he program looking as it does in Fig. 2.1.When you have ent eredt he program by typing it, it's stored int hememoryof the computer in t he form of aset of code numbers.There aret wothingsthatyouneedtoknownow.Oneishowtocheckthat the programisactuallyinthememory;the otherishow tomakethemachine carryouttheinstructionsof theprogram. ThefirstpartisdealtwithusingthecommandLISTthatyouknow already.Youcan use t he SHIFT/ HOME keyst o wipe the screen first if you like,the ntypeLISTandpresstheRETU RNkey.Whenyoupressthe RETURN key - andnot unt il - your program wi llbe listed on the screen. An alternative istopress the F4 key (top row)and then t he RETURN key. You willt henseehowt hecomputer has printedt heitems of the program on the screen, wit h spacesbetween the linenumbers andthe instructions.To make theprogramoperateyouneedanother command,RUN.TypeRUN, then pressthe RETURN key, and you will see the instructionscarri edout. To be moreprecise,youwi llsee: 12.4 4. 5 12.87 5.42857 J42857 14 O.k. That lastli ne should gi ve you some idea of how precisely the MSX computer can carryoutits arithmetic. When you follow t he inst ructi on wordPRINT with apieceof arithmetic like2.8* 4.4,thenwhat isprinted isthe resultof workingoutthatpieceof arit hmet ic. The program doesn'T print 2. 8* 4.4; j ust the resul t of t he action 2.8* 4.4. You can, incidentally, obtain the whole RUN(RETURN)action justbypressingtheF5key. This program hascarriedout t woof the main computer actions - process andoutput- foryou.Theonlyinputhasbeen theprogram,andwe can't al teranyofthesenumbersint heprogramwithoutalteringt heprogram / 12WorkingwithMSX BASIC 2. 1 shows afour line program which willprint some arithmetic results. The processhereconsistsof fouritemsof arithmetic,eachwithanoutput. 10PRINT5.6+6.8 2 ~ 'PRINT9.2-4.7 30PRINT3. 3*3.9 40PRINT7.6/1.4 Fig. 2. 1. Af ourlineari th meticprogram. Take aclose look at thisbecause there's a lot toget used to in these four lines.To start with, the line numbers are 10,20,30, 40 rather t han 1, 2, 3,4. Thisistoallowspaceforsecondt houghts. If you decidethat youwantto haveanother inst ructionbetweenline10and line 20, then you can type the linenumber15,or11or12or any ot her whole number between 10and 20, andfollowitwit h your new instruction. Even though you have entered this line outof order, the computerwillautomatically place it in orderbetween lines10and20.If younum beryourlines1,2, 3,thenthere'snoroomfor these secondthoughts,thoughyoucanchangelinenumbers if you have to byusing the editing commands. Thisidea of havi ng line numbers that go in tensissocommonthatit' sbuiltintoyourMSXcomputer.If youtype AUTO,orpresstheF2key,andthenpressRETURN,youwillseethe number10appearonthe screen.Youcanthentypet hefirstlineof your program. Whenyou press the RETURN keyat the endof t his first line, the nextli nenumberisautomaticallyselectedforyou.If youhavealineof programwi tht hisnumberalready,anasteriskappearsagainsttheline number.ThisC\.utomaticnumberi ngsystemcansaveyoualotof typing! The nextthing tonotice ishow the numberzeroonthe screen is slashed across.Thisistodist inguishitfromtheletterO.Thecomputersimply won't acceptthe 0inplaceof 0, nor t he 0in place of 0;the slashing makes thisdifferencemoreobvioustoyou,sothatyouarelesslikelytomake mistakes.Thezerothatyouseeon thekeyboardmaybeslashedor not, depending onthe manufacturerof the machine,butitison adifferent key from the 0and is differently shaped.Type some zeros and Os on the screen sothat youcanseethedifference. N ow to more important points. The star or asterisk symbol in line 30 is the symbol t hat the MSX computer uses as a multiply sign. Once again, we can't use the Xthat you might normally use for writing mUltiplication because X isaletter.There'snodividesignonthekeyboardeither,sotheMSX computer, like allother small computers,uses/, the slash sign,in its place. Thisisthe diagonal line which is on the same key as the question mark, not theonewhichslopestheotherwayandisinadifferentplace ondifferent MSXcomputers. So far, so good. The program is entered by typing it just as you see it.You don't needt o leave any space between the line number and the Pof PRINT Inputsand Outputs13 becauset heMSXcomputerwillputoneinforyouwhenitdisplaysthe programont hescreen. Youdon'tneedto leaveaspacefollowing PRINT eit her,andyoucantype?inplaceofPRINTifyouwish.TheMSX computer is very tolerant about this sort of t hing, so don't be surprised when youseeaprogramlistinginthisbookwhichshowswordsruntogether. There are some places where you must leavespaces, however, and we'll deal wit ht heseaswecometothem.Rememberthatyouhaveonlyalimited numberofbytesof memoryavai lable,andeachspaceusesoneof these bytes.Later on, asyoubecome accustomedtoprogrammi ng,you willfind t hatyouneedallthememoryyoucanget.You' llbegl adifyourMSX computer alreadyhas around28000bytesavailable, orallows lots of extra memorytobeadded. Gettingbacktotheprogramexample,youwillhavetopresst he RETURNkeywhenyouhavecompletedeachinstructionlinebefore you type t he next line number.You should end up wi th t he program looking as it does in Fig. 2.1.When you have ent eredt he program by typing it, it's stored int hememoryof the computer in t he form of aset of code numbers.There aret wothingsthatyouneedtoknownow.Oneishowtocheckthat the programisactuallyinthememory;the otherishow tomakethemachine carryouttheinstructionsof theprogram. ThefirstpartisdealtwithusingthecommandLISTthatyouknow already.Youcan use t he SHIFT/ HOME keyst o wipe the screen first if you like,the ntypeLISTandpresstheRETU RNkey.Whenyoupressthe RETURN key - andnot unt il - your program wi llbe listed on the screen. An alternative istopress the F4 key (top row)and then t he RETURN key. You willt henseehowt hecomputer has printedt heitems of the program on the screen, wit h spacesbetween the linenumbers andthe instructions.To make theprogramoperateyouneedanother command,RUN.TypeRUN, then pressthe RETURN key, and you will see the instructionscarri edout. To be moreprecise,youwi llsee: 12.4 4. 5 12.87 5.42857 J42857 14 O.k. That lastli ne should gi ve you some idea of how precisely the MSX computer can carryoutits arithmetic. When you follow t he inst ructi on wordPRINT with apieceof arithmetic like2.8* 4.4,thenwhat isprinted isthe resultof workingoutthatpieceof arit hmet ic. The program doesn'T print 2. 8* 4.4; j ust the resul t of t he action 2.8* 4.4. You can, incidentally, obtain the whole RUN(RETURN)action justbypressingtheF5key. This program hascarriedout t woof the main computer actions - process andoutput- foryou.Theonlyinputhasbeen theprogram,andwe can't al teranyofthesenumbersint heprogramwithoutalteringt heprogram / 14WorkingwithMSX BASIC itself.Try writing aprogramof this type for yourself,and see how the MSX computercarriesoutthecalculationsanddisplayst he answers. This isall veryuseful,butit' s not always convenient to have just a set of answers on t he screen,especiallyif youhave forgotten what the questions were. The MSX computer allows you t opri nt anythi ng you like on the screen, exactly as you typeit,byusingwhatiscalledasIring. 10PRINT"2+2=";2+2 20PRINT"2.5*3.5=u2.5*3.5 30PRINTII9.4-2.2=u9.4-2.2 40PRINT"27.6/2.2=;27.6/2.2 Fig.2.2.Usingquotemarks.Inthisandotherexa mples,t heabbreviation? wasusedinpl aceofthePRI NTinst r uct ionword,butPRI NTappearsi n t he listi ng. Figure2.2ill ustratesthisprinciple.Ineachlinesomeof thetypingis enclosedbetweenquotes(invertedcommas)andsomeisnot.Entert hi s shortprogram and run it.Can you see how very differently the computer has treatedtheinstructions?Whateverwasenclosedbetweenquoteshasbeen printedexactl y as youtyped it.Whatever wasnotbetween quotes isworked out,sot hatthefirstline,forexample,givestheunsurprisingresult: 2+ 2= 4 Nowthere'snothi ngautomaticaboutt his.If youtypeanewline: 15PRINT "2+2=";5* 1.5 t henyou'llgetthe daftreply,whenyouRUNthis,of: 2+2= 7.5 Thecomputerdoesa sit'stoldandt hat' swhatyoutoldittodo.Onlya looneycouldbelievet hatcomputerswouldtakeovertheworld! This is a good poi nt at which totake notice of something else. The li ne) 5 that youaddedhasbeenfittedint oplacebetween lines10 and20 - LIST if youdon' tbelieveit.Noma tterinwhatorderyoutypethe linesofyour progra m,thecomputerwi llsort themintoor derof ascending linenumber foryou.Note alsothatthe computer hasput a spacebetweenthe = and the number.Thisdoesn't a lwayshappen,t hough.Thisspaceis reservedfora minussign,soifwewant t omake sure t hatanumberwi thaminus signis separatedfromthe=sign,weneedtoadd aspacebetweenthe= andthe finalquotemarks. The otherimportantpoint aboutthisexampleisthat it showshowtomakeaprogramdi sp lay whatisbeing done.Asbefore,the command wordPRINT has tobe used t oma ke thi ngs appea r on t he screen, but by using quoteswecanmake t he computer print whateverwe want, not j us tt heresultsofsomearit hmet ic.Trymakingthecomputerprintsome answersfor yourself,usingthisformof program. Inputsand Outputs15 Wit hallof this accumulated wisdom behind us,we can now start to look atsomeotherprintingact ions.PRINT,asfarastheMSXcomputeris concerned,alwaysmeansprint ont othe TV screen. For activat ing apaper printer(hardcopyit'scalled),ther'saseparateinstructionLPRINT (and LLIST forprogramlistings).It' snot an indicationof Welsh design - the L oncemeantlineinthedayswhencomputerpri nterswerehugepiecesof machi neryt hat printedawholelineat atime.Theseinstructionsareof no usetoyouunlessyouhaveaprinterconnected. 10PRINT"THISIS" 20PRINT"THEFANTASTIC" 30PRINT"MSXCOMPUTER" Fig. 2.3. Usi ng t he PRINT instructi on t o place w ords on t he screen, one line f or eachuseofPRINT. Now try t heprogram in Fig.2.3. Try typing the lines in any order you li ke t o establish t hepoint thatthey willbe in line number order when you list the program. When you RUNt he program, the words appear on t hree separate lines. Thisisbecause theinst ruct ionPRINT doesn't j ust mean print on the screen. It alsomeans take anew line and startat the left-handside!You will alsofind,incidenta lly,t hatwhenthewordsonthescreenreacht heline abovethebottomline,allt helinesapart fromthebottomoneappearto move up, and t he top line disappears.This isthe action called scr olling, and it'st hewayt hat themachine dealswit hdi splaying lotsoflinesonascreen whichholdsonly24linesatonetime,count ingthebottomline. Inthisexamplethewordshavebeenplacedbetweenquotemarks,and theyhaveappearedon thescreen justaswetypedthem, but with no quote marksshowi ng. This,t hen,ist he sort of programming t hat is neededwhen youwant t odisplayinstructionsor ot hermessagesonthescreen. Thereal problem, asyou'll see whenyoutry it,is getting the messages t o look really neat..Nothinglooksworsethanprintingwhichhassplitwords,withhal f a wordonone li ne and t herest on t henext li ne. Even at t his st age it's poss ible toma keyourpri ntinglookneatwithsomecare.TypethePRINT"'part, thentypethewordsthatyouwant,andcontinuet ypingH'ithoultouching theRETURN keyunt ilyoureach aposit ion on the screenwhi ch is di rectly underneath the quotemar k. If at thi s point youare inthe middle of aword , t hen erase this wor dby using t he BACKSPACE (8S) key. Nowtype asecond quotemark,andthenpressRETURN.Startanot herli nenow,usi ng PRINT", and then type the rest of the message in the same way.Jfyounever crosst hepoint where aletter comes direct lyunder a quote mark on the line above,youwillneversplitawordacrossalineend.Tryit! N owtheacti onofselectinganewlineforeachPRINTis n' talways convenient,a ndwe can changethe action by using punctuation mar kst hat we call print mod?fiers.Start this ti mebyacqui ring anew habit.Type NEW andthenpresstheRETURNkey.Thisclearsouttheoldprogram.You 14WorkingwithMSX BASIC itself.Try writing aprogramof this type for yourself,and see how the MSX computercarriesoutthecalculationsanddisplayst he answers. This isall very useful,butit' s not always convenient to have just a set of answers on t he screen,especiallyif youhave forgotten what the questions were. The MSX computer allows you t opri nt anythi ng you like on the screen, exactly as you typeit,byusingwhatiscalledasIring. 10PRINT"2+2=";2+2 20PRINT"2.5*3.5=u2.5*3.5 30PRINTII9.4-2.2=u9.4-2.2 40PRINT"27.6/2.2=;27.6/2.2 Fig.2.2.Usingquotemarks.Inthisandotherexa mples,t heabbreviation? wasusedinpl aceofthePRI NTinst r uct ionword,butPRI NTappearsi n t he listi ng. Figure2.2ill ustratesthisprinciple.Ineachlinesomeof thetypingis enclosedbetweenquotes(invertedcommas)andsomeisnot.Entert hi s shortprogram and run it.Can you see how very differently the computer has treatedtheinstructions?Whateverwasenclosedbetweenquoteshasbeen printedexactl y as youtyped it.Whatever wasnotbetween quotes isworked out,sot hatthefirstline,forexample,givestheunsurprisingresult: 2+ 2= 4 Nowthere'snothi ngautomaticaboutt his.If youtypeanewline: 15PRINT "2+2=";5* 1.5 t henyou'llgetthe daftreply,whenyouRUNthis,of: 2+2= 7.5 Thecomputerdoesa sit'stoldandt hat' swhatyoutoldittodo.Onlya looneycouldbelievet hatcomputerswouldtakeovertheworld! This is a good poi nt at which totake notice of something else. The li ne) 5 that youaddedhasbeenfittedint oplacebetween lines10 and20 - LIST if youdon' tbelieveit.Noma tterinwhatorderyoutypethe linesofyour progra m,thecomputerwi llsort themintoor derof ascending linenumber foryou.Note alsothatthe computer hasput a spacebetweenthe = and the number.Thisdoesn't a lwayshappen,t hough.Thisspaceis reservedfora minussign,soifwewant t omake sure t hatanumberwi thaminus signis separatedfromthe=sign,weneedtoadd aspacebetweenthe= andthe finalquotemarks. The otherimportantpoint aboutthisexampleisthat it showshowtomakeaprogramdi sp lay whatisbeing done.Asbefore,the command wordPRINT has tobe used t oma ke thi ngs appea r on t he screen, but by using quoteswecanmake t he computer print whateverwe want, not j us tt heresultsofsomearit hmet ic.Trymakingthecomputerprintsome answersfor yourself,usingthisformof program. Inputsand Outputs15 Wit hallof this accumulated wisdom behind us,we can now start to look atsomeotherprintingact ions.PRINT,asfarastheMSXcomputeris concerned,alwaysmeansprint ont othe TV screen. For activat ing apaper printer(hardcopyit'scalled),ther'saseparateinstructionLPRINT (and LLIST forprogramlistings).It' snot an indicationof Welsh design - the L oncemeantlineinthedayswhencomputerpri nterswerehugepiecesof machi neryt hat printedawholelineat atime.Theseinstructionsareof no usetoyouunlessyouhaveaprinterconnected. 10PRINT"THISIS" 20PRINT"THEFANTASTIC" 30PRINT"MSXCOMPUTER" Fig. 2.3. Usi ng t he PRINT instructi on t o place w ords on t he screen, one line f or eachuseofPRINT. Now try t heprogram in Fig.2.3. Try typing the lines in any order you li ke t o establish t hepoint thatthey willbe in line number order when you list the program. When you RUNt he program, the words appear on t hree separate lines. Thisisbecause theinst ruct ionPRINT doesn't j ust mean print on the screen. It alsomeans take anew line and startat the left-handside!You will alsofind,incidenta lly,t hatwhenthewordsonthescreenreacht heline abovethebottomline,allt helinesapart fromthebottomoneappearto move up, and t he top line disappears.This isthe action called scr olling, and it'st hewayt hat themachine dealswit hdi splaying lotsoflinesonascreen whichholdsonly24linesatonetime,count ingthebottomline. Inthisexamplethewordshavebeenplacedbetweenquotemarks,and theyhaveappearedon thescreen justaswetypedthem, but with no quote marksshowi ng. This,t hen,ist he sort of programming t hat is neededwhen youwant t odisplayinstructionsor ot hermessagesonthescreen. Thereal problem, asyou'll see whenyoutry it,is getting the messages t o look really neat..Nothinglooksworsethanprintingwhichhassplitwords,withhal f a wordonone li ne and t herest on t henext li ne. Even at t his st age it's poss ible toma keyourpri ntinglookneatwithsomecare.TypethePRINT"'part, thentypethewordsthatyouwant,andcontinuet ypingH'ithoultouching theRETURN keyunt ilyoureach aposit ion on the screenwhi ch is di rectly underneath the quotemar k. If at thi s point youare inthe middle of aword , t hen erase this wor dby using t he BACKSPACE (8S) key. Nowtype asecond quotemark,andthenpressRETURN.Startanot herli nenow,usi ng PRINT", and then type the rest of the message in the same way.Jfyounever crosst hepoint where aletter comes direct lyunder a quote mark on the line above,youwillneversplitawordacrossalineend.Tryit! N owtheacti onofselectinganewlineforeachPRINTis n' talways convenient,a ndwe can changethe action by using punctuation mar kst hat we call print mod?fiers.Start this ti mebyacqui ring anew habit.Type NEW andthenpresstheRETURNkey.Thisclearsouttheoldprogram.You 16WorkingwithMSX BASIC mightalsoliketousetheSHIFT! HOMEkeystoclearthescreen.If you don'tusetheNEWaction,t here'sachancethatyouwillfindlinesof old programsgettinginthewayof newones.Eachtimeyoutypealineyou deleteanyline that hadthat same li nenumber inanolder program,butif there is alinenumbert hat youdon't useinthe newprogram it wi llremain st ored.In Fig. 2.3,forexample, theline15that you added wouldbeleftin storeevenwhenyoutypedanewli ne10andanewline20. 1'")PRINT"Thi sis iI; 20PRINT"thegreat"; 30PRINT"MSXsystem." Fig.2.4. Theeff ectofsemi col onsonPRINTlines. Trythe program inFig.2.4. There' s a veryimportant difference bet ween Fig.2.4andFig.2.3,asyou'llseewhenyouRUNit.Theeffectof a semicolonfoll owingthelastquoteinalineistopreventthenextpieceof printingstartingonanewli neattheleft- handside.WhenyouRUN t hi s program, allof t he words appear on one line . It would have been much easier j usttohaveonelineof programthatread: 10PRINT "This is the great MSX system." to dothis,buttherearetimes when youhave tousethe semicolon to force two different pTint items on to the same li ne. We' lllook at this sort of thing in laterprogram examples.Meanti me,lookalso athow Ihave placeda space bet weenthelastletterandthelastquotemarkinlines10and20.The semicolon does n' t j ustorder the computer to prevent a new line being t a k e n ~ italsoforcesittoplaceoneitemrightupagainstanot her.If youleftno spaces,thewords'i s'and't he'wouldbeprintedas'isthe"and'great'and 'MSX' as 'greatMSX'. Try removing the spacesand see for yourself.(Turn to Chapter12 t o read how to edit out aspace or any other character if you want to avoid having to type t he whole li ne again.) Rows andcolumns Neatprintingisamatterof arranging yourwordsandnumbersintorows andcolumns,sowe' lltakeacloserlook at t hispart icular art now.To start wit h, weknow already that the inst ruction PRINT will cause a new line to be selected, so the actionof Fig.2.5should not come as too much of a surprise. Line10containsanovelty,though. intheformof twoinst ruct ionsinone line. The inst ructions are separated by a colon (:) and you can, i f you like, have severalinstructionsfo ll owingonelinenumberinthisway,takingseveral screen li nes.So long ast henumberof characters int he line does not take up more than seven lineson the screen, yo u can put instruct ions together inthis way. In a mU/lislal ement line of