home *** CD-ROM | disk | FTP | other *** search
/ SPACE 2 / SPACE - Library 2 - Volume 1.iso / apps / 82 / tutorpas.eng < prev    next >
Encoding:
Text File  |  1986-11-20  |  21.8 KB  |  556 lines

  1. 0660103030566
  2. 1
  3. 2page #
  4. 9[....................................................]
  5.  
  6.  
  7. ëFirstlessonin
  8. Ç
  9.  
  10. ü******PASCAL******
  11.  
  12.  
  13. bySERGEVAILLANCOURT
  14.  
  15.  
  16. ÇWHYPASCAL?
  17.  
  18.      Untiltheendofthe60's,animportantaspectofprogram
  19. writingwasthattheyhadtobewrittenintheshortestpossible
  20. timeinordertosavethecompaniessomemoney.Thismentalitywas
  21. foundtobesomewhatflawedforthesimplereasonthatthe
  22. programmers,havinglesstimetowritetheprograms,oftentraded
  23. readabilityforspeed.Themaintenanceandupdatingofthese
  24. programswasthereforelenghtier,moreexpensiveand,sincesucha
  25. programhasanaverageusefullifeofabout10years,...
  26.  
  27.      Neartheendofthatdecade,anindividualnamedüNIKLAUS
  28. WIRTHÇcreatedastructuredlanguagethatüÇfinallyansweredthe
  29. programmer'sneedsforreadableandmaintainablecode.Hecalled
  30. thatlanguage"üPASCALÇ".
  31.  
  32. ëStructureofaPASCALprogramÇ
  33.  
  34. äPROGRAM
  35. Ç|
  36. Programname
  37. |
  38. Program'sparameterlist
  39. |
  40. declarations
  41. |
  42. äBEGINüÇ⇦---+
  43. ||
  44. instructionsüÇ⇧
  45. üÇ||
  46. +---⇦---+---⇨---+
  47. |
  48. äEND.
  49. Ç|
  50. (figure1.)
  51.  
  52.  
  53.      Forclarity,theconventionfromnowonwillbethatall
  54. wordsinäITALICSÇarePASCALreservedwordsandthattheyhavea
  55. specialsignificanceinthis environment.Youmustthereforeuse
  56. themonlywheretheybelongandthesamegoesforthe"ä;Ç"
  57. (semicolon),the"."(period),andthe"ä,Ç"(comma).
  58.  
  59. Figure1explainsthestructureofaüPASCALÇprogram.
  60.  
  61. àPROGRAMÇ:Alwaysstartaprogramwiththisreservedword.
  62.  
  63. Programname:Anidentifierofyourchoice.Notethatthe
  64.                identifiermustbeanalphanumericstring
  65.                     startingwithaletter.
  66.  
  67. Programparameterlist:IdentifiersusedforInput/Output.
  68. Fornow,theonlytwoparameterswe
  69.                               willuseareàINPUTÇandàOUTPUTÇ,for
  70.                               thekeyboardandthescreen,
  71.                               respectively.
  72.  
  73. "à;äÇ"(Semicolon):Indicatestothecompilerthatthe
  74.                          programheaderendshere.
  75.  
  76. Declarations:Identifiesconstants,datatypes,variables,
  77. procedures,andfunctions.
  78.  
  79. àBEGINÇ:Theprogramstartswiththisreservedword.
  80.  
  81. Instructions:Tellstheprogramwhattodonext.
  82.  
  83. "ü:Ç"(Colon):Usedbetweenprograminstructions.
  84.  
  85. "àENDÇ"and"ü.Ç"(Period):Usedtospecifytheendofthe
  86. compilation.
  87.  
  88. Hereisaprogramthatwillwrite"Hello, my friend"tothe
  89. screen.
  90.  
  91. àPROGRAMÇdisplay(àOUTPUTÇ)à
  92.  
  93. BEGIN
  94. Çäwriteln;
  95. writelnÇ('Hello,myfriend');
  96. àEND.
  97.  
  98. Ç(üProgram1Ç)
  99.  
  100.      Onthefirstline,wefindthereservedwordàPROGRAM,Çthe
  101. nameoftheprogram,aswellastheprogram'sparameterlist.
  102. Sincethisprogramonlywritestothescreen,theonlyparameter
  103. wewillneedisàOUTPUTä.
  104. Ç     Wehavenodeclarationsandthus,westarttheprogramonthe
  105. secondlinewithàBEGINÇ.Onthethirdline,wefindanewreserved
  106. word,äwritelnÇwhichallowsustowriteonscreenandletsus
  107. proceedtothenextline.
  108.  
  109.      Thesetwolinesareinstructionsandareseparatedbya"à;Ç"
  110. (Semicolon).
  111.  
  112.      Andfinally,thelastlineendstheprogramwith"àEND.Ç"
  113.  
  114. ìWRITEêandìWRITELNäÇ
  115.  
  116.      Thesetwoinstructionsallowwritingtothescreen.The
  117. differencebetweenäWRITEÇandäWRITELNÇisthatthelattercausesa
  118. carriagereturn,i.e.:thecursorisrepositionnedatthestartof
  119. thenextline,justlikewithüPRINTÇinBASIC.äWRITEÇdoesnotmove
  120. thecursorafteritsexecution,justlikeüPRINT;ÇinBASIC.
  121.  
  122. ThesyntaxforäWRITEÇandäWRITELNÇisasfollows:
  123.  
  124. àWRITEÇoràWRITELNÇ
  125. |
  126. (
  127. |⇦--------+
  128. parameter(s),
  129. |⇨--------+
  130. )
  131.  
  132. (üFigure2Ç)
  133.  
  134.      Theseparametersmaybevariables,constants,characters,or
  135. stringsofcharacters.Wewillexaminelaterthesubjectof
  136. variablesandconstants,butfornow,let'sexamineanexample
  137. withcharactersandstrings.
  138.  
  139. àPROGRAMüÇdisplay(àOUTPUTÇ);
  140. àBEGIN
  141. WRITEüÇ('H','e','l','l','o');
  142. (*writesthecharactersH,e,l,l,o,formingthe
  143. wordHello*)
  144. àWRITELNÇ('Hello')
  145. (*writesthestring"Hello"*)
  146. àEND.Ç
  147.  
  148. (üProgram3Ç)
  149.  
  150.      Youhaveprobablynoticedthetextbetween(*and*).These
  151. arecommentsinPASCAL,identicaltoREMsinBASIC.Fromnowon,
  152. allprogramsherewillbecommentedinthisfashion.
  153.  
  154.      Itispossible,witheachparameterofàWRITEüÇandàWRITELNÇto
  155. specifytheamountofrightjustificationoftheoutputbyadding
  156. ":x",wherexstandsfortheamountofjustificationneeded.Ex.:
  157.  
  158. àWRITEÇ('Hello:15')
  159.  
  160.      Atthetimeofexecution,theoutputwillbe:
  161.  
  162. ^^^^^^^^^^^Hello
  163.  
  164. Forclarity,eachcaret(^)representsasinglespace.
  165.  
  166.      Thevalueafterthe":"maybeaconstant,asintheabove
  167. example,oravariable.Ifthisvalueisinferiortothenumberof
  168. characterstobeprinted,thentheinstructionwilloverflowthe
  169. valuegivenandignorethejustification.
  170.  
  171. ëDECLARATIONS
  172. Ç
  173. Thereare5typesofdeclarations:
  174.  
  175. Labels;
  176. Constants;
  177. Datatypes;
  178. Variables;
  179. ProceduresandFunctions.
  180.  
  181. ëLABELSÇ
  182.  
  183.      Theyare"pointers"muchlikeGOTOsinBASIC.Theyareseldom
  184. usedsincetheycaneasilybereplacedwithotherinstructionsand
  185. besides,they"break"thestructureoftheprogram.Somepeople
  186. usethemasa"breakpoint",awaytogetoutofaprogramwhen
  187. there'sanerrorintheexecutionofthatprogram.Thattopicwill
  188. beexaminedinalatertutorialonthesubject.
  189.  
  190. ëCONSTANTSÇ
  191.  
  192.      Aconstantisrepresentedbyanidentifier(theconstant's
  193. name)thevalueofwhichcannotbechangedduringtheprogram's
  194. execution.Thisisoftenusedbyprogrammersbecauseitaffords
  195. themimpeccableclarityandeasestheprogram'smaintenance.
  196.  
  197. Syntax:
  198.  
  199. CONSTANT
  200. |⇦--------+
  201. identifier|
  202. |⇧
  203. =;
  204. ||
  205. value|
  206. |⇨--------+
  207. ;
  208.  
  209. (üFigure3Ç)
  210.  
  211.      Thevaluemaybeaninteger,arealnumber,acharacter,ora
  212. stringofcharacters,thevalueofwhichmustbebetweensingle
  213. quotes(').
  214.  
  215. Examples:header='AccountingSystem';
  216. pi=3.1416;
  217. CarriageReturn=13;
  218. MyName='SergeVaillancourt';
  219.  
  220.      Somecompilershavepredefinedconstantsthatdonothaveto
  221. bedeclaredlike,forexample:äMAXINTÇwhichrepresentsthe
  222. largestusableinteger,i.e.:32767
  223.  
  224. ëVARIABLESÇ
  225.  
  226.      Avariableisanidentifier(thevariable'sname),the
  227. valueofwhichmaybechangedduringtheprogram'sexecution.
  228. Thus,avariableiscomposedoftwoparts:the"container"which
  229. isthenameofthevariable,andthe"contents"whichisthevalue
  230. ofthevariable.
  231.  
  232. Awayofgivingavariableavalueisby"Assignment".
  233.  
  234. Variable
  235. |
  236. ü:=Ç
  237. |
  238. Expression
  239.  
  240. (üFigure4Ç)
  241.  
  242. Examples: a:=10
  243. x:=10+2
  244. name:='Serge'
  245.  
  246. The":="symbolisformedbyusingthecharacters":"and"="
  247. withoutaninterveningspacebetweenthetwo.
  248.  
  249.      InPASCAL,everyvariablemustbedeclared.
  250.  
  251. Variable
  252. +----⇨-------|-------⇦----+
  253. |Variable'sname|
  254. ;|-------⇨----+
  255. |Variable'stype
  256. +----⇦-------|
  257. ;
  258.  
  259. (üFigure5Ç)
  260.  
  261. Thevariable'stypeidentifiesthekindofvariableyouareusing:
  262. aninteger,arealnumber,acharacter,etc....
  263.  
  264. ëTHETYPESÇ
  265.  
  266. Whenwedeclareavariable,wemustgiveitaTYPEattribute.
  267.  
  268. Example:
  269.  
  270. àPROGRAMÇexample(àOUTPUTÇ);
  271. àVARäÇ
  272. i,number1:äintegerÇ(*typeinteger*)
  273. number2:ärealÇ(*typereal*)
  274. character:ächarÇ(*typecharacter*)
  275. àBEGINÇ
  276. i:=12;(*assignstoianinitial
  277. valueof12*)
  278. number1:=i+3;(*assignstonumber1an
  279. initialvalueofi+3*)
  280. àwritelnüÇ('I=',i,'andNumber1='number1);
  281. number2:=3.8;(*assignstonumber2an
  282. initialvalueof3.8*)
  283. character:='A';(*assignstocharacter
  284. thecharacter'A'*)
  285. àwritelnÇ('Number2=',number2);
  286. àwritelnÇ('Character=',character);
  287. i:=number1+i;(*itakesavalueequal
  288. tonumber1+i*)
  289. àwritelnÇ('iisnowequalto',i);
  290. àEND.Ç
  291.  
  292. (üProgram3Ç)
  293.  
  294.      Inthelastexample,thereare4variablesdeclaredas3
  295. differenttypes.
  296. ü
  297.      ëINTEGERÇ:Thesearethevariablesthattakewholenumbers
  298. (integers).Allowedvaluesareintherangeof
  299. -32768and32767inclusive.Ifaninteger
  300. overflowsthesevalues,youmustdeclareitas
  301. typeREAL.
  302.  
  303. ëREALüÇ:Thesearethevariablesthattakerealnumber
  304. values.Thesevaluesareintherangeof1.0*10
  305. exponent-38and1.0*10exponent38.InPASCAL,the
  306. waytorepresentthemantissaandexponentisthe
  307. following:3.8E2
  308.  
  309. whichmeans3.8*10tothesecondpower,or380.It
  310. isalsopossibletoassignavaluetoavariable
  311. withoutmantissaorexponent.Thus,thesetwo
  312. examplesarevalid:
  313.  
  314. number:=3.8E2;
  315. number:=380.0;
  316.  
  317. Itisalsousefultospecifythatwecanalso
  318. formattheoutputofarealnumberbyindicating
  319. thenumberofdigitsanddecimalswantedfor
  320. output.Example:
  321.  
  322. àPROGRAMÇdisplay(àOUTPUTÇ)
  323. àVARÇ
  324. number:àREALÇ;
  325. àBEGINÇ
  326. number:=3.1234;
  327. àWRITELNÇ(number:6:2);
  328. àEND.Ç
  329.  
  330. (üProgram4Ç)
  331.  
  332.      TheàWRITELNÇ(number:6:2)indicatesthatwewanttowritethe
  333. valueofNUMBERwithin6placesand2digitsofdecimals.The
  334. outputwillbelikethis:
  335.  
  336. ^^3.12
  337.  
  338. ëCHARÇ:Thistypeofvariablecanbeassignedacharacter.
  339. Thecharactermaybealetter,adigit,orany
  340. otherlike%,@,&,etc...Herearesomeassignment
  341. examples:
  342.  
  343. charact:='e';
  344. letter:='Q';
  345. number:='4';
  346. a:='a';
  347. c:='^';
  348.  
  349. TherearealsootherTYPESwhichwewillexaminein
  350. thenextlesson.
  351.  
  352. ëOPERATORSÇ:
  353. ---ONINTEGERS--
  354.  
  355. ADDITION(+),example:a:=3+4;aisequalto7and
  356. mustbedeclaredas
  357. anàINTEGER
  358. Ç
  359. SUBTRACTION(-),example:a:=3-4;aisequalto-1and
  360. mustbedeclaredas
  361. anàINTEGERÇ
  362. MULTIPLICATION(*),
  363. example:a:=3*4,aisequalto12and
  364. mustbedeclaredas
  365. anàINTEGERÇ
  366.  
  367. DIVISION(/),example:a:=3/4,aisequalto0.75
  368. andmustbedeclared
  369. asaàREALÇnumber.
  370. INTEGERDIVISION(DIV),
  371. example:a:=3DIV4,Theresultisthe
  372. integerpartofthe
  373. division,ex.:a:=3
  374. DIV4,isequalto0
  375. andmustbedeclared
  376. asanàINTEGERÇ.
  377. REMAINDEROFDIVISION(MOD),
  378. example:a:=3MOD4,Theresultisthe
  379. remainderofthe
  380. operation,ex.:a:=3
  381. MOD4,isequalto3
  382. andmustbedeclared
  383. asanàINTEGERÇ.
  384.  
  385. --ONREALNUMBERS--
  386.  
  387. ADDITION(+),example:a:=4.48+2.0;
  388. aequals6.48andisdeclared
  389. asaàREALÇnumber.
  390. SUBTRACTION(-),example:a:=4.48-2.0;
  391. aequals2.48andisdeclared
  392. asaàREALÇnumber.
  393. MULTIPLICATION(*),example:a:=4.48*2.0;
  394. aequals8.96andisdeclared
  395. asaàREALÇnumber.
  396. DIVISION(/),example:a:=4.48/2.0;
  397. aequals2.24andisdeclared
  398. asaàREALÇnumber.
  399.  
  400. ëTHESTANDARDARITHMETICFUNCTIONSÇ
  401. =================================
  402.  
  403.      +-----------------------------------------------------------+
  404. |PASCALfunction|meaning|typeb|typea|
  405. +------------------------+--------------+---------+---------+
  406. |a:=äABSÇ(b)|unsigned|integer|sameas|
  407. ||valueof(b)|orreal|b|
  408. |a:=äSQRÇ(b)|squareof|integer|sameas|
  409. ||(b)|orreal|b|
  410. |a:=äSINÇ(b)          |sineof(b)|integer|real|
  411. |                       |             |orreal||
  412. |a:=äCOSÇ(b)          |cosine      |integer|real|
  413. |                       |of(b)       |orreal|    |
  414. |a:=äARCTANÇ(b)       |arctangent   |integer|real|
  415. |                        |of(b)       |orreal||
  416. |a:=äSQRTÇ(b)         |squareroot|integer|real|
  417. |                        |of(b)       |orreal||
  418. |a:=äLNÇ(b)           |naturallog|integer|real|
  419. |                        |of(b)       |orreal||
  420. |a:=äEXPÇ(b)          |exponentof|integer|real|
  421. ||(b)          |orreal||
  422. |a:=äTRUNCÇ(b)|integerpart|real|integer|
  423. ||of(b)       |||
  424. |a:=äROUNDÇ(b)|truncated|real|integer|
  425. ||partof(b)|||
  426. +------------------------+--------------+---------+---------+
  427.  
  428. (üFigure6Ç)
  429.  
  430.  
  431. ëREADandREADLNÇ
  432.  
  433.      WehaveseenwithàWRITEÇandàWRITELNÇ,howtodisplaythe
  434. outputonscreen.Theonlythingisthatwhatweweredisplaying
  435. wasalreadyincludedintheprogram.Withwhatweknow,ifwe
  436. wantedtowriteaprogramthataverages5numbers,thisistheway
  437. wewouldproceed:
  438.  
  439. àPROGRAMÇaverage(àOUTPUTÇ);
  440. àVARÇ
  441. ave:àREALÇ;
  442. àBEGINÇ
  443. ave:=(70.0+75.5+55.8+60.3+85.0)/5;
  444. àWRITELNÇ('Theaverageis',ave:5:1);
  445. àEND.Ç
  446.  
  447. (üProgram5Ç)
  448.  
  449.      Thismini-programeffectivelyaveragesfivenumbers,but
  450. becomesinefficientwhenweneedtochangethevaluestobe
  451. averaged,theonlywaybeingtomodifytheprogram.Butthereisa
  452. solution:
  453.  
  454. àPROGRAMÇaverage2(àINPUT,OUTPUTÇ);
  455. àVARÇ
  456. nb1,nb2,nb3,nb4,nb5:àREALÇ;
  457. (*5numberstoaverage*)
  458. ave:àREALÇ;(*average*)
  459. àBEGINÇ
  460. àREADLNÇ(nb1,nb2,nb3,nb4,nb5);(*Keyboardentry*)
  461. ave:=(nb1+nb2+nb3+nb4+nb5)/5;(*calculateaverage*)
  462. àWRITELNÇ('Theaverageis',ave:5:1);
  463. àEND.Ç
  464.  
  465. (üProgram6Ç)
  466.  
  467.      WhatwenoticehereisàREADLNÇ.Thisinstructionallowsus
  468. toenterthevaluesfromthekeyboard,aboutinthesamemanneras
  469. withINPUTinBASIC.Fromthenon,itispossibletoreusethe
  470. programwithoutmodifyingit.
  471.  
  472. TherelationbetweenàREADÇandàREADLNÇisthesameaswithàWRITEÇ
  473. andàWRITELNÇ.
  474.  
  475. Syntax:àREADÇoràREADLNÇ
  476. |
  477. (
  478. |---⇦---+
  479. Variable|
  480. |---⇨---+
  481. )
  482.  
  483. (üFigure7Ç)
  484.  
  485. ëTheìFOR...DOëLoopÇ
  486.  
  487.           Let'suseouraveragingprogramagain.It'snotvery
  488. usefulthewaywewroteitbecauseitonlyallows5numberstobe
  489. averaged.Whatifwewanttoaverage6numbers?Doitoverand
  490. overagain?
  491.  
  492. OnesolutiontothisproblemistousetheàFOR...DOÇ
  493. instructions.
  494.  
  495. àPROGRAMÇaverage3(àINPUT,OUTPUTÇ);
  496. àVARÇ
  497. nbentries(*numberofentriesneeded*)
  498. i:àINTEGERÇ;(*loopcounter*)
  499. nbr,(*valuereadfromkeyboard*)
  500. total,(*totalofthevalues*)
  501. ave:àREALÇ;(*calculatedaverage*)
  502. àBEGINÇ
  503. àWRITEÇ('Inputnumberofentriesneeded');
  504. (*promptstheuserforinput*)
  505. total:=0;(*initializetotaltozero*)
  506. àREADLNÇ(nbentries);(*readsfromthekeyboard*)
  507. (*thenumberofentriesneeded*)
  508. àFORÇi:=1àTOÇnbentriesàDOÇ
  509. (*foreachentry,repeatthefollowing*)
  510. àBEGINÇ(*startstheloop*)
  511. àREADLNÇ(nbr);(*readsanumber*)
  512. total:=total+nbr;(*addnumbertototal*)
  513. àENDÇ;(*fori*)(*endstheloop*)
  514. ave:=total/5;(*calculatesaverage*)
  515. àEND.Ç
  516.  
  517. (üProgram7Ç)
  518.  
  519.      IfyouunderstandthemeaningofàFOR...DOÇ(whichisthe
  520. sameasFOR...NEXTinBASIC)younoticethatwhatiscontained
  521. betweentheàBEGINÇandtheàENDÇoftheàFORÇloopwillexecuteas
  522. longastheloopcounter(representedbyi)hasnotexceededthe
  523. maximumvalue.TheàBEGINÇandàENDÇinstructionsareneededonly
  524. whenthereismorethanoneinstructioncontainedintheàFOR...
  525. DOÇloop.
  526.  
  527.      ThecountermaybeoftypeàINTEGERÇ,àREALÇ,àCHARÇ,or
  528. scalar(tobeexaminedinafuturetutorial).It'salsopossible
  529. todecrementthecounterinsteadofincrementingbyreplacingthe
  530. àTOÇwithaàDOWNTOÇ.
  531.  
  532. Syntax:    àFORÇ
  533. |
  534. variablecounter
  535. |
  536. :=
  537. |
  538. expression
  539. |
  540. àTOÇoràDOWNTOÇ
  541. |
  542. expression
  543. |
  544. àDOÇ
  545. |
  546. instruction
  547.  
  548.  
  549.      Thenextlessonwilldealwithmatrixvariables.Wewillalso
  550. studyothertypesofvariables,otherinstructions,andstart
  551. explainingPROCEDURESandFUNCTIONS.
  552.  
  553. üSergeVaillancourt
  554. March1986Ç
  555.  
  556.