Getting Started With Pascal Programming

2y ago
69 Views
8 Downloads
517.28 KB
46 Pages
Last View : 9d ago
Last Download : 3m ago
Upload by : Mya Leung
Transcription

Getting Started With PascalProgrammingHow are computer programs createdWhat is the basic structure of a Pascal ProgramVariables and constantsInput and outputPascal operatorsCommon programming errorsIntroduction to program design and problem solvingJames TamReminder: About The Course Textbook It’s recommended but not a required purchase. However the course notes are required for this courseJames TamGetting Started With Pascal Programming1

Reminder: How To Use The Course Resources They are provided to support and supplement this class. Neither the course notes nor the text book are meant as asubstitute for regular attendance to lecture and the tutorials.James TamReminder: How To Use The Course Resources (2)procedure add (var head: NodePointer;var newNode : NodePointer);vartemp : NodePointer;beginif (head NIL) thenhead : newNodeelsebegintemp : head;while (temp .next NIL) dotemp : temp .next;temp .next : newNode;end;newNode .next : NIL;end;James TamGetting Started With Pascal Programming2

Reminder: How To Use The Course Resources (2)eprocedure add (var headak on : NodePointer;mvar: NodePointer);ps newNodevarlas ch u tcaat ge s)temp :sNodePointer;s ou c ed ( oteibeginm t y ss s ni thenasouif (headyth u mNIL)claIf re heados: newNode’ysu at neh eowelsembeginsotemp : head;while (temp .next NIL) dotemp : temp .next;temp .next : newNode;end;newNode .next : NIL;end;.wcla hensu ss m yoyo pple ak u doain ur o me e su mant h t go w n t t h r e t h k e ie e n no etxa na tes slid at yo toms reeu(if y mem caus s witou be e y hdo r it oun’t in)James TamBut Once You’ve Made An Attempt To Catch Up Ask for help if you need it There are no dumb questionsImage from “The Simpsons” FoxGetting Started With Pascal ProgrammingJames Tam3

Don’t Forget: How To Succeed In This Course1.2.3.4.Practice things yourselfMake sure that you keep up with the materialLook at the material before coming to lectureStart working on things earlyJames TamComputer ProgramsBinary is the language of the computerTranslatore.g., gpc1) A programmerwrites a computerprogram2) A translatorconverts theprogram into aform that thecomputer canunderstand3) Anexecutableprogram iscreated4) Anybody who hasthis executableinstalled on theircomputer can run(use) it.James TamGetting Started With Pascal Programming4

TranslatorsConvert computer programs to machine languageTypes1) Interpreters Each time that the program is run the interpreter translates the program(translating a part at a time).If there are any errors during the process of interpreting the program, theprogram will stop running right when the error is encountered.2) Compilers Before the program is run the compiler translates the program (compiling it allat once).If there are any errors during the compilation process, no machine languageexecutable will be produced.If there are no errors during compilation then the translated machine languageprogram can be run.James TamCompiling Programs: Basic ascalcompilerinputgpcoutputa.outJames TamGetting Started With Pascal Programming5

The Smallest Pascal Programprogram smallest;beginend.Note: The name in the header "smallest" should match the filename "smallest.p". Youcan find an online version of this program in the Unix file system under/home/231/examples/intro/smallest.p (the compiled version is called "smallest").James TamCreating And Compiling Programs On TheComputer Science NetworkTo begin creating the Pascal programin Unix type "XEmacs filename.p"Text editorXEmacsPascal programfilename.p(Unix file)PascalcompilergpcMachine languageprogramTo compile the program inUnix type "gpc filename.p"a.out (Unixfile)To run the program in Unixtype "./a.out"James TamGetting Started With Pascal Programming6

Source Code Vs. Executable FilesSource code (e.g., smallest.p file) A file that contains the Pascal program code.It must end with a ‘dot-p’ suffix (program name.p).Can be viewed and edited.Cannot be executed.program smallest;begin::end.Executable code (often it’s the “a.out” file) A file that contains machine language (binary) code.By default this file will be called “a.out”.It cannot be directly viewed or edited (meaningless).It can be executed.ELF A B A @ @ @ @ @ @ @ @ @ @ B @ B @ @ @ A @ A Zh @ @ @4 @ B\263\370 @ @ @ @ @4 @ @ E @( @ ] @ Z @ @ @ F @ @ \::James TamBasic Structure Of Pascal ProgramsProgram name.p (Pascal source code)Part I: HeaderProgram documentationprogram name (input, output);Part II: Declarationsconst:Part III: Statementsbegin:end.James TamGetting Started With Pascal Programming7

Details Of The Parts Of A Pascal ProgramPart I: Header Parts:1) Program documentation- Comments for the reader of the program (and not the computer)(**)Marks the beginning of the documentationMarks the end of the documentation2) Program heading- Keyword: program, Name of program, if input and/or output operationsperformed by the program. Example(** Tax-It v1.0: This program will electronically calculate your tax return.* This program will only allow you to complete a Canadian tax return.*)program taxIt (input, output);DocumentationHeadingJames TamProgram DocumentationProgram documentation: Used to provide information about acomputer program to another programmer: Often written inside the same file as the computer program (when you seethe computer program you can see the documentation). The purpose is to help other programmers understand how the program codewas written: how it works, what are some of it’s limitations etc.User manual: Used to provide information about how to use aprogram to users of that program: User manuals are traditionally printed on paper but may also be electronicbut in the latter case the user manual typically takes the form of electronichelp that can be accessed as the program is run. The purpose is to help users of the program use the different features of theprogram without mention of technical details.James TamGetting Started With Pascal Programming8

Program Documentation (2) It doesn’t get translated into binary. It doesn’t contain instructions for the computer to execute. It is for the reader of the program: What does the program do e.g., tax program. What are it’s capabilities e.g., it calculates personal or small business tax. What are it’s limitations e.g., it only follows Canadian tax laws and cannotbe used in the US. What is the version of the program- If you don’t use numbers for the different versions of your program thenconsider using dates. How does the program work.- This is often a description in English (or another high-level) language thatdescribes the way in which the program fulfills its functions.- The purpose of this description is to help the reader quickly understand how theprogram worksJames TamDetails Of The Parts Of A Pascal Program (2)Part II: Declarations List of constants More to come later during this term regarding this sectionPart III: Statements The instructions in the program that actually gets things doneThey tell the computer what to do as the program is runningStatement are separated by semicolons ";“Example statements: display a message onscreen, prompt the user for input,open a file and write information to that file etc. Much more to come later throughout the rest of the term regarding thissectionJames TamGetting Started With Pascal Programming9

Performing CalculationsOperationSymbol (Operator)Addition Subtraction-Multiplication*Real number division/Integer divisionDIVRemainder (modulo)MODJames TamStoring InformationInformationCould it change?(Use a variable)Never changes.(Use a named constant)James TamGetting Started With Pascal Programming10

VariablesSet aside a location in memory This location can store one ‘piece’ of informationUsed to store information (temporary) At most the information will be accessible as long as the program runsTypes: integer – whole numbers real – whole numbers and fractions char – a single character: alphabetic, numeric and miscellaneous symbols(in UNIX type “man ascii”) boolean – a true or false valueUsage (must be done in this order!) Declaration Accessing or assigning values to the variablesPicture from Computers in your future by Pfaffenberger BJames TamDeclaring VariablesSets aside memoryMemory locations are addressed through the name of the variableRAMName ofvariableRESERVEDJames TamGetting Started With Pascal Programming11

Declaring VariablesDeclare variables between the ‘begin’ and ‘end.’Part I: HeaderProgram documentationprogram name (input, output);Part II: Declarationsconst:Part III: StatementsbeginDeclare variables here (just after the ‘begin’end.James TamDeclaring Variables (3)Format:var name of first variable : type of first variable;var name of second variable : type of second variable;Example:The full example can be found in UNIX under:/home/231/examples/intro/variableExample1.p (variableExample1 for thecompiled version).program variableExample1;beginvar height : real;Variablevar weight : real;declarationvar age: integer;end.James TamGetting Started With Pascal Programming12

Global Variables Variables declared outside of the begin-end pair.program anExample;var num1 : integer;beginvar num2 : integer;Global variable: DON’T DOIT THIS WAYNon-global variable (localvariable): DO IT THIS WAYend. For now avoid doing this (additional details will be providedlater in the course): generally this is regarded as badprogramming style.James TamVariable Naming Conventions Should be meaningful Any combination of letters, numbers or underscore (can'tbegin with a number and shouldn't begin with an underscore) Can't be a reserved word (see the “Reserved Words” slide) Avoid using predefined identifiers (see the “StandardIdentifiers” slides) Avoid distinguishing variable names only by case For variable names composed of multiple words separate eachword by capitalizing the first letter of each word (save for thefirst word) or by using an underscore.James TamGetting Started With Pascal Programming13

Reserved WordsHave a predefined meaning in Pascal that cannot be whilewhileFor more information on reserved words go to the url: http://www.gnu-pascal.de/gpc/index.htmlJames TamStandard IdentifiersHave a predefined meaning in Pascal that SHOULD NOT be changedPredefined constants false true maxintPredefined types booleancharintegerrealtextPredefined files input outputFor more information on standard identifiers go to the url: http://www.gnu-pascal.de/gpc/index.htmlGetting Started With Pascal ProgrammingJames Tam14

Standard Identifiers (2)Predefined dsinsqrsqrtsucctruncFor more information on standard identifiers go to the url: http://www.gnu-pascal.de/gpc/index.htmlJames TamStandard Identifiers (3)Predefined ewriteunpackwritewritelnFor more information on standard identifiers go to the url: http://www.gnu-pascal.de/gpc/index.htmlGetting Started With Pascal ProgrammingJames Tam15

Variable Naming Conventions (2) Okay:- tax rate- firstName Not Okay (violate Pascal syntax)-1abctest.msggood-dayprogram Not okay (bad style)- x- writelnJames TamAccessing VariablesCan be done by referring to the name of the variableFormat:name of variableExample:numJames TamGetting Started With Pascal Programming16

Assigning Values To VariablesFormat:Destination : Source; 1Example:The full example can be found in UNIX under:/home/231/examples/intro/variableExample2.p (variableExample2 for thecompiled version).program variableExample2;beginvar height : real;var weight : real;var age: integer;weight : height * 2.2;end.NO!1 The source can be any expression (constant, variable or mathematical formula)James TamAssigning Values To Variables (2)program variableExample2;beginvar height : real;var weight : real;var age: integer;height : 69;A betterweight : height * 2.2;approachend.Important lesson: ALWAYS initialize your variables to somedefault starting value before using them.James TamGetting Started With Pascal Programming17

Assigning Values To Variables (3)Avoid assigning mixed types:program variableExample;beginvar num1 : integer;var num2 : real;num1 : 12;num2 : 12.5;num2 : num1;RareNot allowed!num1 : num2;end.James TamReminder: Variables Must First Be Declared BeforeThey Can Be Used! (The Right Way)Correct:RAMprogram anExample;beginvar num : integer;num : 888;end.num888James TamGetting Started With Pascal Programming18

Reminder: Variables Must First Be Declared BeforeThey Can Be Used! (The Wrong Way)Incorrect:RAMprogram anExample;beginnum : 888;var num : integer;CompileError:end.Where isnum?James TamNamed ConstantsA memory location that is assigned a value that CANNOT be changedDeclared in the constant declaration ("const") sectionThe naming conventions for choosing variable names generally apply toconstants but the name of constants should be all UPPER CASE. (You canseparate multiple words with an underscore).Format:constNAME OF FIRST CONSTANT value of first constant;NAME OF SECOND CONSTANT value of second constant;etc.James TamGetting Started With Pascal Programming19

Named Constants (2)Examples:constTAX RATE 0.25;SAMPLE SIZE 1000;YES True;NO False;James TamDeclaring Named ConstantsNamed constants are declared in the declarations sectionPart I: HeaderProgram documentationprogram name (input, output);Part II: DeclarationsconstDeclare constants herePart III: Statementsbegin::end.James TamGetting Started With Pascal Programming20

Named Constants: A Compilable Exampleprogram anExample;constTAX RATE 0.25;SAMPLE SIZE 1000;YES True;NO False;MY FIRST INITIAL ‘J’;beginvar grossIncome : real;var afterTaxes : real;grossIncome : 100000;afterTaxes : grossIncome – (grossIncome * TAX RATE);end.James TamPurpose Of Named Constants1) Makes the program easier to understandpopulationChange : (0.1758 – 0.1257) * currentPopulation;Vs.constMagic Numbers(avoid wheneverpossible!)BIRTH RATE 0.1758;DEATH RATE 0.1257;beginpopulationChange : (BIRTH RATE – DEATH RATE) *currentPopulation;James TamGetting Started With Pascal Programming21

Purpose Of Named Constants (2)2) Makes the program easier to maintain- If the constant is referred to several times throughout the program,changing the value of the constant once will change it throughout theprogram.James TamPurpose Of Named Constants (3)program population (output);constBIRTH RATE 0.1758;DEATH RATE 0.1257;beginvar populationChange : real;var currentPopulation : real;populationChange : (BIRTH RATE - DEATH RATE) * currentPopulation;if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)else if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)end.James TamGetting Started With Pascal Programming22

Purpose Of Named Constants (3)program population (output);constBIRTH RATE 0.5;DEATH RATE 0.1257;beginvar populationChange : real;var currentPopulation : real;populationChange : (BIRTH RATE - DEATH RATE) * currentPopulation;if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)else if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)end.James TamPurpose Of Named Constants (3)program population (output);constBIRTH RATE 0.1758;DEATH RATE 0.01;beginvar populationChange : real;var currentPopulation : real;populationChange : (BIRTH RATE - DEATH RATE) * currentPopulation;if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)else if (populationChange 0) thenwriteln(‘Births: ‘, BIRTH RATE, ‘ Deaths:’, DEATH RATE, ‘ Change:’,populationChange)end.James TamGetting Started With Pascal Programming23

Storing InformationInformationCould it change?(Use a variable)Never changes.(Use a constant) Fractional numbers:use a “real” Fractional numbers:use a “real” Whole numbers: usean “integer” Whole numbers: usean “integer” Single character: usea “char” Single character: usea “char” Only true or false:use a “boolean” Only true or false:use a “boolean”James TamOutput Displaying information onscreen Done via the write and writeln statements Write: displays the output and nothing else (the cursor remains on the line) Writeln: displays the output followed by a newline (the cursor moves to the nextline)Format (literal string of characters):write (‘a message');orwriteln(‘a message');James TamGetting Started With Pascal Programming24

Output (2)Example (literal string of characters):The complete example can be found in UNIX under:/home/231/examples/intro/outputExample1.p (outputExample1 for thecompiled version).program outputExample1 e('line3');end.StyleconventionJames TamOutput Of The Contents Of Variables AndConstantsFormat:write( name of variable or constant );orwriteln ( name of variable or constant );James TamGetting Started With Pascal Programming25

Output Of The Contents Of Variables AndConstants (2)Example:The complete example can be found in UNIX under:/home/231/examples/intro/outputExample2.p (outputExample2 for thecompiled version).program outputExample2 (output);constACONSTANT 888;beginvar num : integer;num : 7;writeln(ACONSTANT);writeln(num);end.James TamMixed OutputIt’s possible to display literal strings of characters and thecontents of variables and constants with a single write or writelnstatement.Format:write('message', name of variable , 'message' );orwriteln('message', name of variable , 'message' );James TamGetting Started With Pascal Programming26

Mixed Output (2)Example:The complete example can be found in UNIX under:/home/231/examples/intro/outputExample3.p (outputExample3 for thecompiled version).program outputExample3 (output);constACONSTANT 888;beginvar num : integer;num : 7;writeln('ACONSTANT: ', ACONSTANT);writeln('num ', num);end.James TamOutput: How Do You Make It Look Nice?P1: How to make output line align/justify from line-to-line?A1: Set the field width parameterP2: How to specify the number of places of precision for theoutput of real numbers?A2: Set the parameter for the number of places of precision (onlyworks for real numbers)James TamGetting Started With Pascal Programming27

Formatting OutputAutomatic formatting of output Field width: The computer will insert enough spaces to ensure that theinformation can be displayed. Decimal places: For real numbers the data will be displayed inexponential/floating point form.Manually formatting of output:Format:write or writeln ( data : Field width for data1 : Number decimal places for real data1 );Examples:var num : real;num : 12.34;writeln(num);writeln(num:5:2);1 These values can be set to any non-negative integer (zero or greater).James TamFormatting Output (2)If the field width doesn’t match the actual size of the field Field width too small – extra spaces will be added for integer variablesbut not for other types of data. Examples:var num : integer;num : 123456;writeln(num:3);writeln('123456':3); Field width too large – the data will be right justified (extra spaces will beput in front of the data). Examples:var num : integer;num : 123;writeln(num:6);writeln('123':6);James TamGetting Started With Pascal Programming28

Formatting Output (3)If the number of decimal places doesn’t match the actual numberof decimal places. Set the number of decimal places less than the actual number of decimalplaces – the number will be rounded up. Example One:var num : real;num : 123.4567;writeln (num:6:2); Set the number of decimal places greater than the

Getting Started With Pascal Programming 1 James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables and constants Input and output Pascal operators Common programming errors Introduction to program design and

Related Documents:

Free Pascal: it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS, and several other platforms. Turbo51: it is a free Pascal

Free Pascal it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32- and 64-bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms. Turbo51 It is a free Pascal com

Free Pascal: it is a free compiler for running Pascal and Object Pascal programs. Free Pascal compiler is a 32 and 64 bit Turbo Pascal and Delphi compatible Pascal compiler for Linux, Windows, OS/2, FreeBSD, Mac OS X, DOS and several other platforms. Turbo51: it is a free Pasc

Turbo Pascal Programming CMPSC 132: Programming Languages WILBEN R. PAGTACONAN Instructor, CAS-DCS, MMSU Turbo Pascal is a software development system that includes a compiler and an integrated development environment (IDE) for the Pascal programming language running on DOS, developed by

Nama Pascal diambil dari seorang ahli matematika yang bernama Blaise Pascal yang menemukan mesin hitung pertama. Bahasa Pascal dirancang untuk menyelesaikan masalah dari berbagai kalangan pemakai, mulai dari para mahasiswa, pendidik, dan ilmuwan. Salah satu kompiler pascal yang terkenal dan tercepat adalah

includes IBM Pascal, Microsoft Pascal, Microsoft QuickPascal, Turbo Pascal and Turbo Pascal for Windows. This manual assumes

This manual contains the complete description of the Compaq Pascal programming language. It supersedes DEC Pascal Language Reference Manual, order AA-PWVSB-TK. Revision/Update Information: This is an updated manual. Software Version: Compaq Pascal

In recent years, there has been an increasing amount of literature on . A large and growing body of literature has investigated . In recent years, several studies have focused on