Http Gigi Nullneuron Net Comp Pascal Htm

download Http Gigi Nullneuron Net Comp Pascal Htm

of 30

Transcript of Http Gigi Nullneuron Net Comp Pascal Htm

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    1/30

    Pascal Tutorial

    By Daniel D'Agostino

    Contents

    Pascal Language Tutorial

    Introduction to PascalOverview of the Programming ProcessBasic Inputand OutputThe CRTUnitConditionalStatementsLoopsFile HandlingSubprogramsData typesBGI Graphics

    Pascal Reference

    Index of Pascal Reserved WordsIndex of CRT ColoursIndex of AcronymsUseful Links

    Table of ASCII CodesTutorial Tree

    Pascal Language Tutorial

    Introduction to Pascal

    In the late 1950s, an international committee led by Peter Naur developed ALGOL, a high-level language intended for scientific computing. This language was

    Convert webpages or entire websites to PDF Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    2/30

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    designed to be platform-independent, making it more flexible, but also making it harder to write compilers for it on the various platforms it supported. ALGOL wasmostly abandoned by programmers, except to describe algorithms (hence the name,ALGOrithmic Language).

    During the next decade, several computer scientists worked to develop ALGOL to improve it and eliminate its drawbacks. Among them was Dr. Niklaus Wirth ofthe Swiss Federal Institute of Technology, who in 1971 published his specification of Pascal, a new high-level language named after Blaise Pascal, the 17th-century mathematician and philosopher who in 1642 invented an adding and subtracting machine, i.e. one of the first forms of computer.

    Nowadays, Pascal has mostly withered from the professional programming scene. However, although obsolete compared to the languages there are today,Pascal is nowhere as forgotten as ALGOL, from which it was forged. Its syntax, mainly based on simple English, makes it very easy to understand, and thusPascal is mainly used nowadays to introduce students to programming.

    Overview of the Programming Process

    The Compiler

    What you will be writing in Pascal is called the source code, i.e. it is the code written by the programmer in a particular programming language.

    The source code needs to be translatedinto machine language(executional codeor object code) that the computer can understand in order to beexecutable. The source code alone is just text; the actual program is the translated code brought to life in machine language.

    A compileris a program which translates source code to object code. Therefore you will need a compiler to program in Pascal. There are a number of freecompilers around on the internet (such as Free Pascalor Dev-Pascal), but the one used as standard is Borland Turbo Pascal. Pascal code that works withTurbo Pascal is not guaranteed to work with other compilers.

    Borland has released up to version 5.5 of Turbo Pascal for free at their software museum, but you will need to create a Borland user account to be able todownload it. The latest version of Turbo Pascal is 7.0 (which is obviously much better than 5.5), but it is not free.

    Once you write your source code in the compiler, you need to compile the source code to translate it into machine language. After compilation, you may run theprogram to test it. If compilation is not successful and an error is shown, you will need to debugthe code to make the program work.

    Note that if you get a message like "Error 200: Division by Zero", then the problem is with the compiler, not with your code. Search for "Pascal patch" in your

    favourite search engine and download the patch. Run it to fix the error.

    Errors in Programming

    There are three kinds of errors encountered when programming:

    Syntax errorsare errors in the code you write so that the compiler cannot understand your code, and the code will not compile. This usually involvesmisspelling a command or forgetting a semicolon at the end of a statement.Runtime or execution errorsare errors halting the flow of the program after it is compiled and run. This usually happens when the wrong type of variableis given in input (e.g. inputting text where an integer should be entered).

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://community.borland.com/museum/http://www.bloodshed.net/http://www.freepascal.org/
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    3/30

    Logical errorsare errors in the sequence of instructions or in the methods of calculation which do not halt the program but produce the wrong results.

    When any error is encountered, you will need to debugthe program, finding and eliminating errors. The compiler will usually tell you the line in which the erroroccurred, and it will also tell you what went wrong. That will help you find errors and fix them.

    Comments

    Any computer language allows you to write commentsin your code, i.e. to make notes about what each part of the code does. This will not increase the size ofthe output program, and is very useful. If you go back to look at your code after a long time, it will be very difficult to understand what you did; comments help you

    to recognise what your code does.

    There are two ways to write comments in Pascal:

    {this is a comment}

    (* this is another comment*)

    Both methods work the same way and may be used on single or multiple lines alike. {or (*begins the comment, and }or *)ends it.

    Basic Input and Output

    The basic program begins with actually giving the program a name (optional), using theprogramkeyword followed by the name you want:

    programcalculator;

    Almost every statement ends with a semicolon.

    The actual instructions of the program go between thebeginand endkeywords:

    programcalculator;

    begin

    end.

    Putting a semicolon afterbeginis optional, because it is the beginning of the main function; it is not a statement or command that is used on one line. Theprogram always ends with a full stop.

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    4/30

    Output

    Thewrite()orwriteln()functions are used to write text on the screen. The only difference between them is thatwriteln()skips a line after what itdisplays, whilewrite()keeps going on the same line.

    To display text, put a text string in the brackets, enclosed by single quotes:

    writeln('What is your favourite song?');write('Nevermind. I do not want to know.');

    You can usewritelnto skip lines. Writing it without the brackets will skip a line without writing anything to the screen:

    writeln;

    The fact that text is enclosed in single quotes means that you cannot use an apostrophe within the string, or the string will end prematurely and give an error.

    Write the apostrophe twice if you want to use it within the string:

    write('It''s Raining!');

    You may concatenateor join two separate strings within thewrite()orwriteln()functions using a comma or plus sign. It is best to use the comma though,because while the plus sign will concatenate text, it will add if you are writing a numeric variable.

    Constants

    In the space between theprogramname and thebeginpoint go many important declarations about variables, constants and other things to be used by theprogram. Among these are, of course, constants. These are numbers of text strings whose value never changes, but is simply used without changing.

    Constants go in the constblock, and have a value assigned to them using the 'equals' sign. They may later be used withwrite()or other functions.

    programconstdemo;

    const pi = 3.141592654; e = 2.718281828;

    begin writeln('The value of pi is ',pi);end.

    Note that in thewriteln()orwrite()functions, single quotes are only used to contain text. Numbers, constants, variables and other data types should not

    Convert webpages or entire websites to PDF Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    5/30

    be enclosed in quotes or will be treated as text.

    Variables

    Variables are much like constants, with the difference that their value is subject to change.

    Like constants, they are declared in the area betweenprogramandbegin, and what you define is not their content but their type.

    A Pascal variable can be of any of the following types:

    integer- whole number within the range -32768x

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    6/30

    Note that you can save space by declaring multiple variables of the same type on the same line, using a comma to separate them.

    var day, year, age : integer; pi, e : real; name, month : string;

    Note also that you do not have to stay declaring or e. A predefined function for exists so all you have to do iswrite()it as follows. Another function existsfor e, which we will see later.

    write(pi);

    Input

    The read()and readln()functions work for input pretty much like howwrite()andwriteln()work for output. A variable is specified in the brackets, andthe user input is stored in that variable:

    varname : string;begin

    writeln('What is your name?'); readln(name); writeln('Pleased to meet you, ', name, '.');end.

    Note that if the program vanishes before showing you the final output, add another readstatement to ask for input before ending the program.

    With numerical input, you can have several numbers inputted at a time; the user will enter each number and press ENTER . This is done by entering multiplevariables in the read()or readln()function, separating them with commas. Here is a practical example of its use:

    programaverage_of_three_numbers;

    varx,y,z:integer;

    begin writeln('Please enter three numbers:'); readln(x,y,z); writeln('Their average is ', ((x+y+z)/3));end.

    Arithmetic Operations

    Convert webpages or entire websites to PDF Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    7/30

    Like any real programming language, Pascal can be used to perform arithmetic operations. There are several symbols involved; we have already seen the use ofthe assignation operator (:=) and two of the arithmetic operations are shown in the previous example. These are the arithmetic operators available in Pascal:

    Operator Operation Data type Example Answer to Example

    + Addition Real/Integer 5+3 8- Subtraction Real/Integer 15-6 9* Multiplication Real/Integer 4*5 20/ Real Division Real/Integer 2.2/1.1 2.0000000000E+00div Integer Division Integer 81 div 9 9

    mod Modulus (Remainder) Integer 5 mod 2 1

    The first three operators should be very straightforward. The Real Division (/) divides two numbers and gives the answer as a decimal, irrespective of whetherthey were integers or decimals. The Integer Division (div), on the other hand, is used to divide two integers and gives the answer as an integer. The Modulus(mod) operator returns the remainder of the division of two numbers.

    You may use brackets to perform some operations before others. The following example illustrates the use of arithmetic operations within a program.

    programtracknums;vara,b,c:integer;

    begin a := 3; {a=3, b=0, c=0 } c := (5*a); {a=3, b=0, c=15} b := (c-a); {a=3, b=12, c=15} a := (cmodb); {a=0, b=12, c=15} c := ((c div 5) + (b-9)); {a=0, b=12, c=6 }end.

    Note that if you are outputting numbers which are to undergo arithmetical operations, putting the operations in brackets in thewriteln()function is just as goodas using the assignation operator:

    a := 5; b := (a+5); writeln(b); {b=10}

    a:=5; writeln((a+5)); {10 is written}

    Ordinal Functions

    Convert webpages or entire websites to PDF Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    8/30

    integerand charare called ordinaldata types. Each integer or character has another before it ( predecessor) and another after it (successor). For example,the successor of 'a'is 'b'and the predecessor of 20is 19.

    For the purpose of finding these predecessors and successors, you may use the following functions:

    Function Description ExamplesOutput ofExamples

    chr() Displays the character corresponding to the ASCII value specifiedchr(97);chr(43);chr(234);

    a+

    ord() Displays the ordinal value of the specified character or integer. In the case of integers, the integer itself is returned. In thecase of characters, the corresponding ASCII value is returned.

    ord(5);ord('a');ord(25);ord('r');

    59725114

    pred() Returns the predecessorpred(39);

    pred('b');

    38

    a

    succ() Returns the successorsucc(8);succ('x');

    9y

    Advanced Mathematical Functions

    A number of advanced mathematical functions are available in Pascal, as illustrated below. Don't expect to understand them without post-secondary

    Mathematical knowledge.

    Function Parameter General Output Example Result

    sin() angle in radians sinx sin(pi); 0cos() angle in radians cosx cos(pi); -1arctan() angle in radians tan-1x arctan(0); 0

    exp() number ex exp(1); 2.7182818285E+00

    ln() positive number lnx ln(exp(1)); 1.0000000000E+00sqr() number x2 sqr(-5); 25

    Convert webpages or entire websites to PDF Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    9/30

    sqrt() positive number x sqrt(390625); 625round() number xrounded to nearest integer round(2.7); 3trunc() number xrounded down to previous integer trunc(2.7); 2abs() number |x| abs(-5); 5

    Random Numbers

    It is often necessary to generate random numbers, especially when games are involved. To generate random numbers, first initialise the generation of random

    numbers using the randomizefunction, then use the random()function to generate a random number between zero and one less than the parameter ofrandom(), i.e. if the parameter is n, then the range in which the generated random number lies is 0x

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    10/30

    The CRT Unit

    One of the best things about high-level programming languages is that the range of functions available to you can be extended by using one or more librarieswhich contain the definitions of the additional functions they let you use.

    In Pascal, these libraries are called units, and they are actually .TPU files in the UNITS folder of your Turbo Pascal compiler.

    You can use units with the useskeyword, which goes in the area betweenprogramandbegin:

    usescrt;

    Once the unit us used, you may then use its functions.

    One of the easiest units to use is the CRT unit. CRT stands for 'Cathode Ray Tube', and refers to the screen; it allows you to manipulate some features of thetext screen such as text colour, text background colour, etc.

    Functions of the CRT Unit

    Clearing the screen

    You can use the clrscrfunction to clear the screen (equivalent to the DOS cls command):

    clrscr;

    Simple as that. This statement clears the screen.

    Most of the next functions we will be seeing use one or more parameters. A parameter is what goes in the function's brackets, for example 'Hi'is theparameter inwriteln('Hi').

    Text Colour and Background Colour

    The textcolor()and textbackground()functions are used to set the colour and background colour respectively of the text you output. As a parameteryou can specify either the name (doesn't need quotes) or the corresponding number of the colour you want. There are sixteen coloursyou can choose from.Notes:

    1. You can only use the first 8 colours (dark colours) for the background.2. If you exceed the greatest colour number (7 for background or 15 for foreground), the colours start over (e.g. 0, 16and 32are all black).3. Adding 128 to the foreground colour will make it blink. However, I wouldn't encourage the use of blinking text... it can be quite annoying.

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    11/30

    The following is an example of the use of these two functions.

    programcolourexample;

    usescrt;

    vara,b:integer;

    begin clrscr; writeln('Enter text colour number you want'); readln(a); textcolor(a); {Text colour changes to the value of 'a'} writeln('Now enter background colour number'); readln(b); textbackground(b); {Background colour changes to 'b'} readln;end.

    The textattrvariable is like a combination of textcolor()and textbackground(). Its general format is thus:

    textattr := (backgroundcolour*16)+textcolour

    backgroundcolourand textcolourrepresent the background and text colour numbers you want.

    Going to a specified (x,y)coordinate in output

    The gotoxy()function will move to a particuar position on the screen, so that whatever you write will be written there. Its syntax is gotoxy(x,y), wherexisthe distance from the left side of the screen and yis the distance from the top of the screen.

    gotoxy(12,9);

    This will move 12 spaces right and 9 spaces down from the top-left point of the screen.

    Delaying

    The delay()function will cause the program to wait for smilliseconds between one command and the next, where sis the parameter of the delay()function:

    delay(3000); {Wait for 3000 milliseconds (3 seconds)}

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    12/30

    Changing text size

    You can change the size of text using the textmode()function. This does not allow you to change the font size as you please, but rather manipulates the widthand height in characters of the screen, resulting in stretched text.

    The normal dimensions of the screen are 80 characters (wide) by 25 characters (high). Thus textmode(co80)is the normal text mode. Usingtextmode(co40)will make only 40 characters fit in one line, so text will be wider. You can also use textmode(font8x8), which normally fits 50 linesinstead of 25, resulting in text being squashed vertically. Finally, textmode(lastmode)switches to the last mode you used. Here is a summary of parameters

    available for the textmode()function:

    co80- 8025 characters (normal)co40- 4025 characters (200% text width)font8x8- (80 or 40)50 characters (50% text height)lastmode- previous text mode

    Note that the width of font8x8depends on which other mode was previously set.

    Reading keypresses

    readkeyis a kind of variable that is given a value when a key is pressed.

    usescrt;varc:char;

    begin c := readkey; writeln(c);end.

    When the user presses a key, the corresponding ASCII value of that key is passed to readkey, and is then assigned to the character variable we declaredearlier. When we write it, the ASCII value is converted back to character format and written to the screen.

    Halting program flow

    The haltcommand can be used to end the program before it reaches the end of the instructions. Whatever is after haltwill not be executed.

    haltmay also be used as a function, with an integer as a parameter. This parameter is used as an exitcode, so that it is returned when the program halts. Zerois the default exitcode if you use it as a command (i.e. without brackets or parameters).

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    13/30

    halt; {Halt with exitcode 0}

    halt(1); {Halt with exitcode 1}

    Note that haltdoes not require the CRT unit to work.

    Sounds

    With the CRT Unit, you can play with sounds. Not complex sound and breathtaking music, but simple DOS beeps. You just have to use the sound()functionwith a frequency as its parameter, delay()the sound for a number of milliseconds specified as its parameter, and then use nosoundto end the sound(otherwise it will continue beeping until you close the compiler).

    It's fun. I tried making the 'Ready, get set, go' beeps they used to do in old racing games:

    programracesnd;

    usescrt;

    begin

    sound(100); delay(200); nosound; delay(1000); sound(100); delay(200); nosound; delay(1000); sound(400); delay(400); nosound; readln;end.

    Conditional Statements

    If

    The ifstatement allows you to determine the program's next course of action depending on whether one or more conditions are true.

    Imagine the program asks the user for his age, and displays a message depending on what he entered. If his age is zero, then write "Are you sure?" If the age isbetween 0 and 40, then write "You're still young!" Otherwise, write "You're really old!"

    programaskage;

    varage, absage:integer;

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    14/30

    begin writeln('Enter your age below.'); readln(age); absage := abs(age); {To handle negative age values} if(absage=0) thenwriteln('Are you sure?'); elseif((absage > 0) and(absage < 40)) thenwriteln('You''re still young!') elsewriteln('You''re really old!'); readln;

    end.

    You should think of the conditional statement as one big command, so that a semicolon is only used to end it all in the final elsestatement, and not thestatements after each then.

    Each single ifstatement as it is only accepts one command. If we were to use other commands besideswriteln(), you would need to have abegin..endblock enclosing them.

    if(absage=0) thenbegin writeln('Are you sure?');

    writeln('Enter your age again'); readln(age) end;

    Note that in this case, each statement except the last one in thebegin..endblock uses a semiconol, and a semicolon after endends the block of commands.This endends with a semicolon because it is only ending a block of commands. The endthat ends with a full stop only ends like that because it is ending thewhole program.

    Logical/Comparative Operators

    As we have seen, commands are executed depending on whether a condition is true. The condition usually depends on whether one or more variables are equalto a given value (like absage = 0) or within a given range (like absage > 39). The variable, in each case, is comparedwith the given value using a logicaloperator.

    The following logical operators may be used:

    Operator Description

    < is less than> is greater than

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    15/30

    >= is greater than or equal to= is equal to

    is not equal to

    Note that the logical operator =is different from the assignation operator :=. One of the most common mistakes in every programming language (apart fromforgetting semicolons) is to mistake one for the other. :=is used to assign a value to a variable; =compares a given value with that of a variable.

    Boolean Operators

    Four other boolean operatorsmay be used to check whether a condition is true. They may be used to join multiple conditions or invert a condition, and theconditions they are associated with depend on whether the variable matches the specified value. In the following examples, numbers are used instead ofvariables to make things clearer.

    not- returns true if the condition is false,e.g.not(6>3)returns FALSEnot(5=3)returns TRUE

    andreturns true if both conditions are true, e.g.(7>5) and(4

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    16/30

    elseif((fage>=20) xor(mage>=20)) then writeln('One of your parents is really young.'); elsewriteln('None of your parents are really young.'); readln;end.

    Case

    Using the ifstatement can sometimes be cumbersome, especially if there are lots of different possivilities of output for each instance of the variable.

    The casestatement is much neater in such cases, as it lists instructions for each instance or range of the variable. Its general syntax is:

    casevariableof instance1: instruction1; instance2: instruction2; elsedefault_instruction;end;

    Here's an example of its use:

    varmark:integer;begin writeln('What was your Physics mark?'); readln(mark); casemark of 0: writeln('Hopeless!'); 1..19: writeln('You''re serious?'); 20..39: writeln('That''s a bad fail.'); 40..49: writeln('You failed, but it was close.'); 50: writeln('You just passed!'); 51..59: writeln('You got a D.');

    60..69: writeln('You got a C.'); 70..79: writeln('Well done! That''s a B.');80..99: writeln('Excellent!');

    100: writeln('Perfect!'); elsewriteln('Huh?'); end; readln;end.

    There are three ways to specify values in the casestatement:

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    17/30

    Specific values (e.g. 100)A range of values (e.g.70..79) - in general,a..bmeans axbMultiple specific values (e.g. 70,75) - these are separated by a comma

    The elsepart is optional, but is useful to handle input outside the range we want it in (e.g. a mark greater than 100).

    Note that if you want more than one instruction to be executed for each case, you need to use abegin..endblock, just like with ifstatements.

    Loops

    Sometimes it is necessary to repeat a command for a number of times. This is called looping, and there are three kinds of loop.

    The for..doLoop

    The for..doloop repeats a command while counting from one number to another. Its general syntax is:

    forvariable:=value1tovalue2do instruction;

    The program will count from value1to value2while executing the instruction.

    Let's say we want to list all of the ASCII characters from zero to 255. Along with the for..doloop, we are going to use the chr()function. We have alreadysaid that its parameter is an integer, and it returns the corresponding ASCII character of its parameter.

    varcharnum : integer;begin forcharnum:=0 to255 do writeln(chr(charnum)); readln;end.

    If you want to count down (e.g. from 255 to 0), replace towith downto.

    Note that abegin..endblock is required for multiple commands, just like with conditional statements.

    Thewhile..doLoop

    Thewhile..doloop is similar to the for..doloop. It repeats the given instructions while a condition is true. This condition is usually associated with a variablelying within a certain range, and it is up to you to increase or decrease the variable in order to eventually break out of the range and end the loop. If you never

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    18/30

    break out of the range, the loop will be infinite.

    programwhiledoexample;

    varx,c:integer;

    begin writeln('Enter a number'); readln(x); x:=abs(x); {To take negative 'x' as positive}

    c:=0;whilec

  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    19/30

    2. Open the text file in a specific mode, depending on whether and how you want to read/write.3. Read/write file.4. close()the file.

    So you first need to declare a variable of type text. This is a special data type purposely used for text files. You will be directly using this variable when opening,reading/writing and closing the file.

    vardatafile:text;

    Once your variable is declared, use the assign()function to associate your variable with a specific file. This function takes two parameters; the first is the

    variable and the second is the name of the file.

    assign(datafile,'data.txt');

    Okay, so the first step is done. The next thing to do is decide what you are going to do with the file, because you will be using a different function depending onthat (for all three functions the parameter is the file variable):

    reset()opens the file for reading.rewrite()opens the file for writing; all contents of the file are erased and new stuff is written. If the file does not exist, it will be created.append()opens the file for writing; new content is added to the end of the file and the original contents of the file are not lost.

    After using one of these functions to open the file in a specific mode, you will want to do whatever you planned to do with the file (read/write data). This is doneusing the same functions you used for writing text to the screen (read(), readln(),write()andwriteln()), with the only difference that as a firstparameter they will take the file variable. Note also that reading functions can only be used if the file was opened with reset(), and writing functions can only beused if either rewrite()or append()was used.

    write(datafile,'Hello!');

    Once you're done, you need to close()the file. Here's a full example.

    programemail_address_book;

    usescrt;

    vardatafile:text; counter:integer; name,email:string;

    begin; clrscr; assign(datafile,'data.txt'); rewrite(datafile);

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    20/30

    forcounter:=1 to3 do begin; {user inputs data} writeln('Enter name ',counter,' out of 3'); readln(name); writeln('Enter that person''s email.'); readln(email); {data is written to file} writeln(datafile,name); writeln(datafile,email);

    end; close(datafile);end.

    This program asks you to input 3 people's name and email address. These are written to a file in successive lines. Organising them by line makes it easier toread them, as you can read by line too. Note that since rewrite()is used, the contents of the data file are erased and replaced with new data. If you want toread the entries, you can use the following example program.

    programreadfile;

    vardatafile:text;

    counter:integer; line:string;

    begin; assign(datafile,'data.txt'); reset(datafile); forcounter:=1 to3 do begin; readln(datafile,line); writeln('Name ',counter,': ',line); readln(datafile,line);

    writeln('Email ',counter,': ',line); writeln; end; close(datafile);end.

    The eof()function

    What if my program allows new entries to be appended to the file so that I don't know how many records there are? In such a case, using a forloop between

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    21/30

    two constant values (line 1and 3above) is useless. Instead, you can read line by line until you reach the end of the file, which is where the eof()(end of file)function returns true. The example program below is a rewrite of the program above, using the eof()function.

    program readfile2;

    vardatafile:text; line:string; linecounter:integer;

    begin;

    assign(datafile,'data.txt'); reset(datafile); linecounter := 1;whileeof(datafile) = false do begin; readln(datafile,line); linecounter := linecounter + 1; {Odd-numbered lines are names; even-numbered lines are addresses} if((linecounter mod 2) = 0) then write('Name ') else

    write('Email '); {Write line number followed by the actual name/email} writeln((linecounter div 2),': ',line); {Skip a line after each email} if((linecounter mod 2) = 1) then writeln; end; close(datafile); readln;end.

    The eoln()function

    eoln()is similar to eof(), but instead marks the end of a line. The following program is an example of its use. Try using it with the sample text file shown afterit. After compiling and running the code as it is, replace eolnwith eofand see the difference.

    programeoln_example;

    usescrt;

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    22/30

    varthefile:text; filechar:char;

    begin; clrscr; assign(thefile,'file.txt'); reset(thefile);whileeoln(thefile) = false do begin; read(thefile,filechar);

    write(filechar); end; close(thefile); readln;end.

    file.txt

    This line will be read.

    This line, on the other hand, will not.

    Subprograms

    In a program, there are several lines of code you might want to use more than once. Simply copying and pasting that code will bloat your source code, making itharder to develop the program. Code that needs to be reused may be written in subprograms (which are functions and procedures). Calling the requiredfunction/procedure will execute the necessary instructions, and save copying and pasting lots of lines of code.

    Procedures

    If all you want is to execute multiple instructions in a given order, the subprogram you need to use is the procedure. A procedure may have its own variables and

    constants, and consists of abegin..endblock, which is where you put the instructions you want. Note that any variables or constants belonging to thesubprogram are not available in the program's mainbegin..endblock - variables (and constants) are restricted to a particular scope(the particularsubprogram, loop or main program). Any subprogram must be definedat the beginning of a program before they can be used, and this is how it is done (ingeneral):

    procedureProc_Name

    const {constants go here}var

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    23/30

    {variables go here}begin; {do something}end;

    The definition goes before the mainbegin..endblock. Proc_Namecan be any name you choose for the procedure. Later, in the main program, you use theprocedure by writing this name, followed by a semicolon, as shown below. Note that a procedure definition can consist of just thebegin..endblock, as thesections for constants and variables may be omitted if empty.

    Proc_Name;

    Parameters

    Variables from the main program flow (which are otherwise not accessible by the subprogram because they are outside its scope) may be used in a subprogramby passing them as parameters. This is done by listing the variables used within brackets after the name of the subprogram. Multiple variables of the same typeare separated by commas, and different variable types are separated by semicolons. The following is a sample program using a procedure and a couple ofparameters.

    programdlg;

    usescrt;

    procedure talk(speaker:integer; dialogue:string);begin; textcolor(speaker); if(speaker = 1) then write('Shopkeeper') elseif(speaker = 2) then write('Joe Black '); write(': '); textcolor(7);

    writeln(dialogue); writeln;end;

    begin; clrscr; writeln('Fictional dialogue.'); writeln; writeln('-----'); writeln; talk(1,'Good morning, sir. May I help you?');

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    24/30

    talk(2,'I''m looking for a girl.'); talk(1,'Aren''t we all?'); talk(2,'No, I mean she works here. Do you know Sandra?'); talk(1,'Of course. Let me call her.'); readln;end.

    Functions

    Functions are like procedures, but they return a value that can be used within the main program. This means that they are not just used to carry out instructions,as procedures are, but they are used to manipulate data and return it for use within the main program flow. Like procedures, they can take constants, variablesand parameters. The only difference in definition is that the function name (or the parameters, if any) must be followed by the type of data that the function willreturn.

    The following is an example of the classic function to multiply two numbers. Of course, here the use of the function could easily be replaced by just using a*bwithin thewriteln, but this is just to show you how it works.

    programmultiply_test;

    vara,b:integer;

    functionmultiply(x,y:integer):integer;begin; multiply := x*y;end;

    begin; writeln('Enter the numbers you want to multiply.'); readln(a,b); writeln(a,' x ',b,' = ',multiply(a,b)); readln;

    end.

    As you can see, the function is assigned a value which is later used in the main program. Since the function consists of a value, calling it on its own like aprocedure would do nothing (even though code canbe added to the function to write the value, or whatever is needed). Instead, this value is used with anotherfunction (in this casewriteln) to show the data it represents.

    Subprogram techniques

    Following are a few things you should know if you want to use subprograms properly in your programs.

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    25/30

    Let's say you have two procedures, defined one after another. If you wanted both procedures to call each other, this would not be possible. The first procedurecannot call the second procedure, which is defined later. The solution is to declare your subprograms before they are defined, like this:

    procedureFirst_Procedure; forward;procedureSecond_Procedure; forward;

    As you can see, declaration involves writing the first line of your definition (including theprocedurekeyword, subprogram name and any parameters; followedby the forwardkeyword. This is called forward referencing.

    Note that apart from calling other subprograms, subprograms may also call themselves. However, if this is done, it should be restricted by the condition of a loop.

    Otherwise, the subprogram would call itself infinitely, causing an infinite loop.

    Data types

    BGI Graphics

    Pascal Reference

    Index of Pascal Reserved Words

    There is a set of reserved words in Pascal that cannot be used as identifiers, i.e. you cannot name variables, constants, functions, etc. with the name of thesereserved words. You will notice if a word is reserved because it will display in white rather than the normal yellow.

    Reserved Word Use

    and Boolean Operatorasm

    array

    begin Beginning of a code blockcase Conditional Statementconst Declaration of Constantsconstructor

    destructor

    div Arithmetic Operatordo Performs the commands in Loopsdownto Counts down in for..doloopselse "Otherwise" command in Conditional Statements

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    26/30

    end End of a code blockexports

    file

    for Loopfunction

    goto

    if Conditional Statementimplementation

    ininherited

    inline

    interface

    label

    library

    mod Arithmetic Operatornil

    not Boolean Operatorobject

    of Specifies each caseof a case statementor Boolean Operator

    packed

    procedure

    program Specifies the program's name (see Basic Input and Output)record

    repeat Loopset

    shl

    shr

    string Data type (see Variables)then Performs the commands in If statementsto Counts up in for..doloopstype

    unit

    until Specifies the break condition of the repeat..untilloopuses Includes units (see The CRT Unit)var Declaration of Variables

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    hil L

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    27/30

    while Loopwith

    xor Boolean Operator

    Index of CRT Colours

    There are 16 CRT colours in Pascal. They are the same 8 colours, but 0-7 are low-intensity and 8-15 are high-intensity. If you exceed 15, the colours start over(e.g. 0, 16 and 32 are all black).

    Number Sample Name

    0 black1 blue2 green3 cyan4 red5 magenta6 brown7 lightgray

    8 darkgray9 lightblue10 lightgreen11 lightcyan12 lightred13 lightmagenta14 yellow15 white

    You can use the following program to list the colours in Pascal.

    programcrt_colour_list;

    usescrt;

    varcounter:integer;

    begin; clrscr; forcounter:=0 to15 do

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    b i

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdf
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    28/30

    begin; textcolor(counter); writeln(counter); end; readln;end.

    Index of Acronyms

    Acronym Full Term Description

    ALGOL Algorithmic Language High-level language developed in the late 1950s by a committee led by Peter Naur (see Introduction to Pascal)

    ASCIIAmerican Standard for CharacterInformation Interchange

    The ASCII Codes are numbers corresponding to a character. See Table of ASCII Codesfor a list or OrdinalFunctionsfor the chr()function which displays ASCII codes

    BGI Borland Graphical Interface The Pascal graphics library provided by Borland.CRT Cathode Ray Tube The Cathode Ray Tube is what makes a monitor or screen. Look it up in a Physics book to see how it works.

    Useful Links

    Learn Pascal- good as a Pascal reference, though not detailed enough to serve as a tutorialRoby's Programming Tutorial- goes into the complex parts of Pascal, not for beginnersPascal Programming- tutorial by a Maltese student, not very user-friendly but can be a good tutorial for beginnersBlaise Pascal- about the mathematician after who the language is named

    Table of ASCII Codes

    Please refer to www.asciitable.com/until I put up this section.

    Tutorial Tree

    Pascal Language TutorialIntroduction to PascalOverview of the Programming Process

    The CompilerErrors in ProgrammingComments

    Basic Input and Output

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    Output

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://www.asciitable.com/http://www.maths.tcd.ie/pub/HistMath/People/Pascal/RouseBall/RB_Pascal.htmlhttp://pascalprogramming.schoolreference.com/index.htmhttp://www.geocities.com/SiliconValley/Park/3230/http://www.taoyue.com/tutorials/pascal/contents.html
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    29/30

    OutputConstantsVariablesInputArithmetic OperationsOrdinal FunctionsAdvanced Mathematical FunctionsRandom NumbersSetting Output Width

    The CRT Unit

    Functions of the CRT UnitClearing the screenText Colour and Background ColourGoing to a specified (x,y)coordinate in outputDelayingChanging text sizeReading keypressesHalting program flowSounds

    Conditional StatementsIf

    Logical/Comparative OperatorsBoolean OperatorsCase

    LoopsThe for..doLoopThewhile..doLoopThe repeat..untilLoop

    File HandlingThe eof()functionThe eoln()function

    Subprograms

    ProceduresParametersFunctionsSubprogram techniques

    Data typesBGI Graphics

    Pascal ReferenceIndex of Pascal Reserved WordsIndex of CRT ColoursIndex of AcronymsUseful Links

    Convert webpages or entire websites to PDF - Use PDFmyURL!

    Table of ASCII Codes

    http://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://pdfmyurl.com/?src=pdfhttp://gigi.nullneuron.net/comp/subprog_techniques
  • 7/26/2019 Http Gigi Nullneuron Net Comp Pascal Htm

    30/30

    Table of ASCII CodesTutorial Tree