172
Roby's Pascal Tutorial Part 1 Contents The Basic of Pascal What you will get after this lesson : 1. The understandings of inner program structure of Pascal. 2. Know Pascal data structure well. 3. Write a simple text-based program. 4. Know how to store and retrieve data from the disk. Well, the first lesson is divided into 14 chapters. CHAPTER 1 -- "Hello, World !" A classic approach to begin the course QUIZ Contains the basic understanding of structured programming in Pascal, simple data and some basic input output commands just to declare "Hello, World !" CHAPTER 2 -- Let's Extend ! QUIZ Extending the first "Hello, World !" with some colors. Know what crt unit is. Doing some assignments and calculations. CHAPTER 3 -- If I... QUIZ Contains the basic understanding of conditional branching and its variants, the case of. This is also a lesson for getting keyboard command, readkey. CHAPTER 4 -- "Constants !" QUIZ Yet, all basic thing about constants in Pascal. CHAPTER 5 -- Loop A Loop QUIZ Contains three form of looping in Pascal: For, Repeat ... Until, and While ... do. CHAPTER 6 -- What the hell are Procedures and Functions QUIZ Contains basic understandings about Procedures and Functions. How to break down the problems and then write the required procedures and/or functions. CHAPTER 7 -- Mastering Array QUIZ Mentions basic understandings about array and how to use it. CHAPTER 8 -- Dancing With Strings QUIZ Contains all basic things needed to modify and process strings. CHAPTER 9 -- Best Records QUIZ Get record basic understandings and how to use it. CHAPTER 10 -- Complex ? Not so ... QUIZ Continues records and extending it into complex data structure. CHAPTER 11 -- It's All Set ! All basic understandings about sets. CHAPTER 12 -- Unit 1 Ready ! QUIZ Writing your own unit, extending the available standard units. CHAPTER 13 -- Read the Text File QUIZ Writing and Reading text files and other applications. file:///F|/Documents/Pascal_Doc/pas/pasles01.html (1 of 2)8/3/2005 7:42:19 ••

Pascal tutorial

Embed Size (px)

DESCRIPTION

Pascal programming language - tutorial with examples and Quizzes

Citation preview

  • Roby's Pascal Tutorial Part 1 Contents

    The Basic of PascalWhat you will get after this lesson :

    1. The understandings of inner program structure of Pascal.2. Know Pascal data structure well.3. Write a simple text-based program.4. Know how to store and retrieve data from the disk.

    Well, the first lesson is divided into 14 chapters. CHAPTER 1 -- "Hello, World !" A classic approach to begin the course QUIZ

    Contains the basic understanding of structured programming in Pascal, simple data and some basic input output commands just to declare "Hello, World !"

    CHAPTER 2 -- Let's Extend ! QUIZExtending the first "Hello, World !" with some colors. Know what crt unit is. Doing some assignments and calculations.

    CHAPTER 3 -- If I... QUIZContains the basic understanding of conditional branching and its variants, the case of. This is also a lesson for getting keyboard command, readkey.

    CHAPTER 4 -- "Constants !" QUIZYet, all basic thing about constants in Pascal.

    CHAPTER 5 -- Loop A Loop QUIZContains three form of looping in Pascal: For, Repeat ... Until, and While ... do.

    CHAPTER 6 -- What the hell are Procedures and Functions QUIZContains basic understandings about Procedures and Functions. How to break down the problems and then write the required procedures and/or functions.

    CHAPTER 7 -- Mastering Array QUIZMentions basic understandings about array and how to use it.

    CHAPTER 8 -- Dancing With Strings QUIZContains all basic things needed to modify and process strings.

    CHAPTER 9 -- Best Records QUIZGet record basic understandings and how to use it.

    CHAPTER 10 -- Complex ? Not so ... QUIZContinues records and extending it into complex data structure.

    CHAPTER 11 -- It's All Set !All basic understandings about sets.

    CHAPTER 12 -- Unit 1 Ready ! QUIZWriting your own unit, extending the available standard units.

    CHAPTER 13 -- Read the Text File QUIZWriting and Reading text files and other applications.

    file:///F|/Documents/Pascal_Doc/pas/pasles01.html (1 of 2)8/3/2005 7:42:19

  • Roby's Pascal Tutorial Part 1 Contents

    CHAPTER 14 -- How About Binary One ? QUIZWriting and Reading binary files and other applications.

    Every lesson has a quiz so that you could evaluate yourself.

    file:///F|/Documents/Pascal_Doc/pas/pasles01.html (2 of 2)8/3/2005 7:42:19

  • Pascal Tutorial - Chapter 1

    "Hello, World !"A Classic Approach to Begin the Lesson

    Welcome !

    Pascal is a structured programming language. It means that everything you program, must be structured and in orderly. No more free gotos and jumps. It has a format. Yeah... right. You don't have to obey it anyway since you COULD extend it to complex ones.

    A format of very simple Pascal programs :

    uses ....

    var

    ...

    begin .... (Your program is here)end.

    The word end here should end with stop ('.'). Every Pascal program blocks begins with the word begin and ends with the word end. Some of the end word ends with semicolon ';' or period '.' or just nothing. That will be described later (not in this lesson).

    For example :Type in these words in your BP, and run it by pressing Ctrl+F9

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (1 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    begin Writeln('Hello, World !');end.

    In this case we don't need the word uses and var. Try to run it. It should display 'Hello, World !' on screen. But perhaps it's too fast. But, how can I view it anyway ? Press Alt+F5.

    What is the word uses for ? It's a kind of terms to declare that we use specific library. Some are standard ones. At first, we use the standard ones that come with every Pascal compiler. The one we will use most is crt unit, since it contains various commands that is suitable for us for this moment.

    What is Writeln for ? Writeln is a command to write something into the screen. If you want to write a sentence, just wrap it with quote ('). And don't forget the pair of brackets and the semicolon. Example :

    begin Writeln('I learn Pascal'); Writeln('Hi, there !');end.

    You will see another messages on screen. View it with Alt+F5 after running it by pressing Ctrl+F9.

    So, you want to clear the screen when the program starts. You need to add the word Clrscr; just after the word begin. But it needs uses crt since Clrscr is one of the commands included in crt library. (Pascal terms for library is unit) So, the above example would become :

    uses crt;

    begin Clrscr;

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (2 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    Writeln('I learn Pascal'); Writeln('Hi, there !');end.

    Try and run it !

    Pascal has a command Write instead of Writeln. Why don't you just try that ? Just replace all the Writeln into Write (of the program above). Run it and see what happens. See the difference ?

    It'll output I learn PascalHi, there !. Stick !

    Sometime, we need to leave a line blank. Suppose we want a blank line between I learn Pascal and Hi, there !. Just insert Writeln; between, and bingo ! Try inserting the Writeln in correct order so it yields :

    I learn Pascal

    Hi, there !

    If you do have a good grip about how to write something on screen, please proceed. Otherwise, you should repeat it once again.

    Now the input parts.

    When we ask computer to receive input from users, we need something to store the input before it is being processed. That was variable. We need it to corporate our program. There are various types of variable and with various range too. Here are some frequently used variable types :

    Pascal Variable Name, Range, and TypeType name Range Type

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (3 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    Shortint -128 to +127 integerByte 0 to 255 integerInteger -32768 to +32767 integerWord 0 to 65535 integerLongint -2146473648 to +2146473647 integerReal -??????? to +??????? fractionalString up to 255 letters non-numericChar 1 letter only non-numericBoolean false / true only logical

    There are many more, but that's all we need for now.

    How to declare our variables ? As we seen in our format previously that we have var section there. That's where we suppose to declare our variables. Here is some example :

    var

    MyAge : Byte; Comments : String;

    To assign variables with values, you need to write this syntax :

    var_name := value;

    This should be written anywhere within begin ... end block, in appropriate location.

    Example :

    var

    MyAge : Byte; Comments : String;

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (4 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    begin MyAge:=19; Comments:='Hi, there ! I'm learning Pascal'; Writeln('I am ',MyAge,' years old'); Writeln(Comments);end.

    Write it down, run it an view it on screen !

    How to get the user's input ? Yeah, that's easy actually. Similar to Write or Writeln, Pascal uses Read and Readln. The difference is that in Read or Readln, we cannot write anything on screen but to get user's input.

    Example :

    var

    MyAge : Byte; Comments : String;begin Write('How old are you ? '); Readln(MyAge); Write('Give us comments: '); Readln(Comments); Writeln; Writeln('I am ',MyAge,' years old'); Writeln(Comments);end.

    Write it down, run it an view it on screen !

    Now, you know how to get user's input. But wait ! If I enter 23.5 in 'How old are you ?' it spouts error ! Yeah, you right ! The value on that question is actually stored in MyAge. MyAge is a Byte variable. So it only accept integer values between 0 to 255. That's the range of it ! It cannot go further. If you want computer to accept fractional values in MyAge, try using Real instead of Byte.

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (5 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    But why when I change it to Real, it outputs erratical numbers ? No, it actually doesn't throw garbage on the screen. It just exponential numbers. For ordinary people -- non technical -- it would be more convenient to view fractional number at 3 or 4 place after the decimal point. Try changing :

    Writeln('I am ',MyAge,' years old');

    to :

    Writeln('I am ',MyAge:2:4,' years old');

    What does it mean ? Why some :2:4 attached to MyAge ? For real numbers, it means : Show 2 place before decimal point and 4 place after decimal point So, when we enter 23.5 for MyAge, it will output :

    I am 23.5000 years old

    Try changing :2:4 with other values. Be creative !

    Can we apply it to the string ? Nope ! But it only accepts just :x. It means that 'I only grant this variable x place on the screen to express its value'. Suppose you change :

    Writeln(Comments);

    to

    Writeln(Comments:5);

    Try writing long comments when the program is running. See what happens. If you enter Programming as the Comment, you will see output :

    Progr

    Ok ! I'm tired of pressing Alt+F5 to view this tiresome tutorial result ! No problem. Just add Readln; just before end. Try it yourself !

    That's all for this time. Refer to the quiz to evaluate your understanding.

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (6 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 1

    Now, select your wayBack to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizTo Chapter 2, about exploring crt units

    file:///F|/Documents/Pascal_Doc/pas/pasl1000.html (7 of 7)8/3/2005 7:42:29

  • Pascal Tutorial - Chapter 2

    Let's Extend !Hi !

    We meet again ! Glad to see you ! Now, let's extend our first program with a little variation. Crt unit does not consist of Clrscr only. It has a lot of interesting functions and procedures. The ones we will discuss this time are :

    1. TextColor and TextBackGround2. TextAttr3. GotoXY4. TextMode5. Sound, Delay, and NoSound

    This chapter is intended to add your interests in programming so the lesson wouldn't be so tiresome. If you want to skip this chapter it's OK since it has no important thing to spot. But beware that every jargon and commands I use in this lesson will be brought to the next ones.

    OK ! Let's give color to our text on screen ! We use Crt unit's procedures: TextColor and TextBackGround. Both accepts value ranging 0 to 15. Example :

    TextColor(14);TextBackground(1);

    It will set the foreground color to yellow and blue background for the next Write or Writeln. Yep ! Easy ! Let's look at full example :

    uses crt;

    begin TextColor(14); TextBackGround(1); Writeln('Hello there !');end.

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (1 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 2

    Run it and see what happens.

    O ho ! That's great ! Yellow over Blue. Try to figure all color values ! A lot of variation could be applied and it's all yours to choose. There's even more convenient than above : Use TextAttr instead. It's a kind of a 'combo' variable. You just assign a value that is :

    (background * 16)+foreground

    Suppose you want a cyan background (or light blue), the number is 3, and black foreground, that is 0. So you would write this:

    TextAttr:=(3*16)+0;

    Then, subsequent writes on screen will be in black over cyan. Easy, eh ?

    If you clear screen AFTER you assign colors, you will found that the entire screen will be wiped to the last assigned color. Suppose you have set color black over cyan, if you clear the screen, the entire screen will be black over cyan ! It's useful if you want alternative background instead of black -- It's boring. Yeah ! Easy !

    Want to have big characters on screen ? Try adding TextMode(CO40);. Well, TextMode is used for changing text mode. Valid values to pass is CO80, that is for return back to normal mode, or LastMode -- that is back to last mode visited, and refer help for more information! Example :

    uses crt;

    begin TextMode(CO40); Writeln('A Real BIG Characters on screen !'); Readln; TextMode(CO80); Writeln('Back to normal'); Readln;end.

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (2 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 2

    Before we continue, I would like to introduce the screen behavior of PCs in text mode. Screen has a resolution. In text mode, screen has either 80 or 40 horizontal resolution (generally) and 25 vertical resolution. It means, the screen could be 80 cols by 25 lines or 40 cols by 25 lines. The setting of TextMode reflects to this : CO40 -- sets the screen to 40 characters wide and 25 lines -- and CO80 -- sets the screen to 80 characters wide and 25 lines too. 40 characters wide causes the screen to "stretch" horizontally, so in result, WIDE characters appear on screen.

    EGA and VGA has a special feature that is also supported by crt unit : an enhanced text mode consists of 43 (when EGA) or 50 lines, instead of 25. We put the value Font8x8 inside TextMode parameter.

    We can also directs our text output at specified location by using GotoXY. It accepts parameters X and Y (both are bytes). Note that X reflects to column position, and Y reflects to line position. Both X and Y must not exceed the range of the current text mode. Run and view this program GOTOXY.PAS to see what's going.

    uses crt;

    Begin TextMode(CO40); GotoXY(8,12); Writeln('At 8,12'); Readln; GotoXY(35,8); Writeln('At 35,8'); Readln; GotoXY(40,20); Writeln('At 40,20'); Readln; GotoXY(30,30); Writeln('Guess'); Readln; TextMode(CO80); Writeln('Back to normal');

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (3 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 2

    End.

    Now, let' s play with sounds ! It's easy ! Start playing the sound with Sound, delay for several times, then NoSound. Let's practice ! Cut and paste this program. Run it in BP.

    uses crt;begin Sound(440); Delay(100); NoSound; Sound(550); Delay(100); NoSound;end

    Sound accepts frequency number and it's a word. It is the value of frequency you want to play. Delay accepts value of words. It reflects how many milliseconds (1/100th of a second) you want to delay. NoSound tells the PC to stop playing the note. If you omit Delay, you may not hear any voices. Try it and figure it out !

    Pascal is able to calculate things and it made programming much easier. OK guys, here is the convention:

    l Addition (+), Subtraction(-), and Multiplication(*) : If both numbers are integers, it yields an integer result. Otherwise, even there's only one is real, the result becomes real.

    m integer with integer = integerm integer with real = realm real with real = real

    l Division(/) : Always yields real result.l Special Division (Div) : It's quite the same as (/), but it always yields integer result.

    Fine, fine. But how can I apply this ? Real life equation Becomes

    y = 5 x 3 y:=5*3; (y is either integer or real)z = 5 + 4 x 3 z:=5+4*3; (z is either integer or

    real)a = 3.14 x 7 x 7 a:=3.14*7*7; (a is always real)

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (4 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 2

    b = 14 x (5 + a)b:=14*(5+a);(b depends on a, if a real, b is always real. If a integer, b may be real or integer).

    Yeah, that's quite an example. But you should know it though. How about the special division :

    a:=22/7; when a is real, it yields result 3.142856 .... so on otherwise, error.

    b:=22 div 7;b is always integer, and it hold 3. Div always round to the floor, I mean not to the top nor not to the nearest integer.Even 98 div 3 will result 32 though normal people consider 32.66666666..... to 33.

    Pascal could convert the real numbers to integers using Trunc and Round. Trunc behaves similarly like Div, it rounds to the floor always. Round is more moderate though, it rounds to the nearest integer. Evaluate the expressions below and see the result.

    uses crt;begin Clrscr; Writeln(Trunc(12.31)); Writeln(Round(12.31)); Writeln(Trunc(31.49)); Writeln(Round(31.49)); Writeln(Trunc(44.59)); Writeln(Round(44.59)); Readln;end;

    OK ! That's all for now ! Shall we have the quiz ?

    Where to go ?

    Back to main page

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (5 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 2

    Back to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 1, 'Hello, World !'To Chapter 3 about branching (IF)

    file:///F|/Documents/Pascal_Doc/pas/pasl1001.html (6 of 6)8/3/2005 7:42:39

  • Pascal Tutorial - Chapter 3

    If I...Hi ! Nice to meet you again. And now, we're getting closer, right ? We will begin our lesson with conditional branching. What is conditional branching anyway ? Well, it's a if not this, do this, else do that ... ummm similar things like that, you know. We have the conditions, and if the conditions are satisfied, do some statements, otherwise do something else. Pascal provides two ways to implement conditional branching. One uses if, the other uses case ... of. Well, let's discuss the first part : if The structure of if in Pascal is like this :

    if condition thenbegin :

    :

    end;

    OR, if you add the else part :

    if condition thenbegin :

    :

    end

  • Pascal Tutorial - Chapter 3

    continue after the word end. Let us examine the excerpt of the code below:

    if counter

  • Pascal Tutorial - Chapter 3

    var

    i : byte;begin writeln('Enter a number = '); readln(i); if i

  • Pascal Tutorial - Chapter 3

    program if5;var

    i : byte;begin writeln('Enter a number = '); readln(i); if i

  • Pascal Tutorial - Chapter 3

    Yes, yes ! You may do if inside the begin..end block after the else too. Why don't you do some experiments ?

    Combining the conditions

    Pascal lets us combine the conditions. Say that if a salesman is qualified to get the project if he has sold 7000 pieces of products and he has at least 3 years of experience. This is the example :

    if (productsold>=7000) and (experienceyear>=3) then qualified;

    Yes, this cannot be run of course. In this example I would like to introduce the and, or, and xor keywords. The keyword and means that it will return true if both conditions are met. It means that the first begin..end block will be executed only if both conditions are true.

    The keyword or means that if there is at least one of the conditions is met (or both), then the first begin..end block will be executed. The keyword xor means that if there is ONLY one condition is met (not both), the first begin..end block will be executed. The keyword not means negating all conditions. Then if the condition is true, it will be considered false and vice versa. Now, take a look at these codes :

    program if6;var

    i, j : byte;begin write('Enter a value for i = '); readln(i); write('Enter a value for j = '); readln(j); if (i>3) and (j>4) then begin writeln('This will be done if i>3 and j>4'); writeln('Now change the "and" with "or" and "xor"');

    file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (5 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 3

    end;end.

    program if7;var

    i : byte;begin write('Enter a value for i = '); readln(i); if not (i>3) then begin writeln('This will be done if i is NOT more than 3'); writeln('So, do you understand ?'); end;end.

    How will it be if the conditions are more than 2 ? Simply wraps them with brackets, two by two. Note : The conditions inside the brackets will be done first. Example, look at this :

    program if8;var

    i, j, k : byte;begin write('Enter a value for i = '); readln(i); write('Enter a value for j = '); readln(j); write('Enter a value for k = '); readln(k); if ((i>3) and (j>4)) or (k>5) then begin writeln('Yeah !!'); writeln('Now change the bracket orders and run it again !'); end;end.

    Case..of

    file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (6 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 3

    Sometimes, you really need to select conditions according some criteria. You're clever ! Use some ifs and let it be done ! But how if the criterium was quite long and complex ? I'm sure that it would be a daunting task to have an if for each. How could we categorize the criteria with some similarities and simplify the problem.

    Suppose we have to do the grading system for our campus. Say, if the student has 80 or more deserves an A. 70 to 79 is for B, 60 to 69 is C, 50 to 59 is D, and 49 or below is E. The if example would be like this : (Note that mark is a byte)

    if mark>=80 then grade:='A'else { 79 or below goes here } if mark>=70 then grade:='B' else { 69 or below goes here } if mark>=60 then grade:='C' else { 59 or below goes here } if mark>=50 then grade:='D' else { 49 or below goes here } grade:='E';

    Wow, that's pretty long. Now see this :

    case mark of 80..100: grade:='A'; 70..79: grade:='B'; 60..69: grade:='C'; 50..59: grade:='D'; else grade:='E'; end;

    file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (7 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 3

    Simple and elegant ! Now, let's learn about readkey statement. It is one of the commands included in crt unit, like clrscr. What it does ? It receives the ASCII code of pressed keyboard button. Well, what is ASCII code anyway? It is some sort of codes that is defined for computers. If we pressed the keyboard, it produces some sort of code, and then the computer translates it into the ASCII code, the code we commonly (programmers) know.

    Note for advanced programmers :Don't laugh at this, I have to explain what ASCII code exactly to the non-programmer folks in a practical and easy way without going into the complicated talks ! Yes, we know the "origin" keyboard codes. I do too.)

    Readkey is a function, returning a char value. OK, let's see how it works !

    program test_readkey;uses crt;var

    c : char;begin c:=readkey; case c of #8 : writeln('You presses backspace'); #9 : writeln('You presses tab'); #13: writeln('You presses enter'); #27: writeln('You presses escape'); #32: writeln('You presses space'); else writeln('You presses other key'); end;end.

    The program simply waits for a keypress then detects it and quits. Now you asked : Why do we use the # sign ? Because it denotes a character with a code. Suppose #8 means a character with a code of 8. Why don't we use the .. like the previous example ? Because in this case we don't specify ranges of values while the first example did. Like 80..100 means from 80 to 100.

    Let us detect the arrow keys. Arrow keys, just like function keys, are extended. It means file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (8 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 3

    it generates a special codes. Now, here is the code to trap them :

    program trap_arrow;uses crt;var

    c : char;begin c:=readkey; if c=#0 then { If extended codes, } begin c:=readkey; { read the code once more } case c of #72: writeln('Up arrow'); #75: writeln('Left arrow'); #77: writeln('Right arrow'); #80: writeln('Down arrow'); end; end;end.

    How to detect the ASCII number ? How do you know that ? Easy, with ord. Suppose you want to know the ASCII codes for each keyboard keys. Do this :

    program trap_key;uses crt;var

    c : char;begin c:=#0; while c#27 do begin c:=readkey; if c=#0 then { If extended codes, } begin

    file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (9 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 3

    c:=readkey; { read the code once more } writeln('Extended : ',ord(c)); end else writeln(ord(c)); end;end.

    Now, press keyboard keys, and see the codes. Combine it with Ctrl, Alt, and Shift and see what happens. To understand the program above, you need to know what while means. The statements inside the while will be repeated on and on as long as the condition (c#27) is met. It means the c:= readkey; if c=#0 ... will be repeated as long as c is not equal to character 27. Since character 27 is escape, then the program simply runs until user presses Esc. More about while and other repetitional commands will be explained thoroughly in chapter 5.

    Where to go ?

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 2 about extending first programTo Chapter 4 about constants in Pascal

    file:///F|/Documents/Pascal_Doc/pas/pasl1002.html (10 of 10)8/3/2005 7:42:49

  • Pascal Tutorial - Chapter 4

    Constants !Hello ! We meet again ! Get ready for this short one ! In real world, we meet many constants, such as pi = 3.1415926513... or e = 2.7182818284529... Many of these are impractical number so that it is quite hard for us to remember, at least for some of us. Pascal has a good facility to use the constants. Even it has predefined ones, like pi.

    How to define our own constant ? Easy, just like a variable definition, we just give const above our constants AND start tayloring our needs.

    const :

    myconst = 1234; :

    :

    (Like variable definition)

    We just omit the constant type, Pascal will understand it. We can use it just like a normal variable. Example :

    const myconst = 1234;var

    i : word;begin i:=40; writeln(i*myconst);end.

    Easy, no ? But heed my word, constants is unchangeable. If you try to change it, Pascal will say error. Wait a minute ! I heard that Pascal's constants can be changed somewhere in the program. You are absolutely right ! Now, the declaration becomes :

    file:///F|/Documents/Pascal_Doc/pas/pasl1003.html (1 of 3)8/3/2005 7:43:31

  • Pascal Tutorial - Chapter 4

    const myconst : mytype = thevalue;

    example:

    const abc : word = 1234;

    You may not declare constants with values exceeding the type, like these :

    const aaa : word = 100000; { Illegal because word is integer ranging 0-65535 } bbb : byte = 123.44; { Illegal because of the fractional part } ccc : string = 123; { Illegal because incompatible type }

    Clear ? How can we modify them inside our program ?

    const myconst : word = 1234;var

    i : word;begin i:=40; myconst:=1000; writeln(i*myconst);end.

    Easy, just like a normal variable, doesn't it ? That's all for this chapter !

    file:///F|/Documents/Pascal_Doc/pas/pasl1003.html (2 of 3)8/3/2005 7:43:31

  • Pascal Tutorial - Chapter 4

    Where to go ?

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 3 about branching(if, case..of)To Chapter 5 about looping in Pascal(for, while..do, repeat..until)

    file:///F|/Documents/Pascal_Doc/pas/pasl1003.html (3 of 3)8/3/2005 7:43:31

  • Pascal Tutorial - Chapter 5

    Loop A Loop

    Hi ! Nice to meet you ! We meet again in Loop a loop. This course suppose to be long and you feel quite bored, don't you ? Well, let's make it quite straight forward.

    In many cases in programming, we need to repeat processes. In that case, we need some loops. Pascal understands it, therefore it provides three types of loops :

    1. For ... to ... do2. While ... do3. Repeat ... until

    Well, let's look inside them :

    1. For ... to ... do

    Syntax :

    For variable := fromwhat to what dobegin :

    :

    statements / commands :

    :

    end;

    Example : Suppose i is an integer

    For i:=1 to 5 dobegin writeln(i);

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (1 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    if i=5 then writeln('Finished !');end;

    It yields 1, 2, 3, 4, 5, then the message 'Finished !'. You see that inside the begin-end block, you could add any commands you want. If there is only one command inside it, you may omit the begin..end, just like if we have studied before. Suppose you omit the if i=5 ..., so inside the begin..end we have only writeln(i);. We can omit the begin..end, then it becomes :

    For i:=1 to 5 do writeln(i);

    If we want to count backwards, i.e. from 5 to 1, we just change to into downto, so check this out :

    For i:=5 downto 1 do writeln(i);

    How about if we want to step more than one, i.e. 1, 3, 5, 7, 9, ...? BASIC provides the STEP how about Pascal ? Well, in this case, Pascal DOES NOT provides such, but if you are creative, you are able to do it. This applies to fractional step as well. BUT, Pascal does include special feature. Check this :

    { Suppose c is a char variable }

    For c:='A' to 'Z' do write(c,' ');

    You may also write For c:='Z' downto 'A' do write(c,' '); as well. You may even write this : (Suppose b is a boolean)

    For b:=false to true do writeln(b);

    And many even stranger cases than this, if you have studied type statement.

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (2 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    2. While...do

    Well, if you have learned BASIC, you will find that While...do is quite the same as WHILE ... WEND. The syntax is :

    While conditions dobegin :

    (statements / commands) :

    end;

    Before we enter the begin..end block, FIRSTLY it checks whether the condition(s) are satisfied. If not, it just skips it out, or else it does any commands inside begin..end. When it reaches the end, it checks the condition again. If it is satisfied, then loop again. If not, go out. It goes on and on. The logic is like this :

    For example :

    i:=1;While i

  • Pascal Tutorial - Chapter 5

    end;

    You may also combine conditions with AND, OR, or XOR. If Pascal does not provide STEP like BASIC, you can change the for into while that has a lot more flexibilities.

    3. Repeat ... Until.

    The syntax is :

    Repeat :

    statements / commands :

    Until condition;

    Unlike While...do, Repeat...Until does not check for conditions at first. It just enters the block and do anything inside. Beware that Repeat...Until does not require begin...end. AT THE END, it then checks whether the conditions are satisfied or not. If SO, it QUITs. That is the third difference from the While...do. If it does not, it simply loops back. So, the logic is like this :

    For example :

    (uses crt first)Repeat Until Keypressed;

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (4 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    OR :

    i:=1;Repeat writeln(i); i:=i+1;Until i>5;

    In While...do and Repeat...until there is a chance to get an infinite loop. Simply give an impossible conditions. But remember, that this also a drawback if we don't use it carefully. Example :

    While 25;end;

    (2 is always less than 4, so (3 is never be able to exceed 5, soWhile...do get an infinite loop) Repeat...until goes forever).

    Or you might just:

    While true do OR Repeatbegin (bla bla bla ...) (bla bla bla ...) Until false;end;

    (They yield the same effect as previous examples : infinite loops).

    You may also nest the loop, i.e. a for inside another for, a While in another While, etc. And even, you may nest one form of loop inside another form, like a for

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (5 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    inside Repeat...Until. Example :

    Repeat :

    For ... do begin :

    end; :

    Until ...;

    It is perfectly legal.

    How about if I want to bail out in a middle of loops ? Easy, use Break. Example :

    begin for i:=1 to 10 do begin writeln(i); if i=5 then break; end; writeln('Finished !'); end.

    It yields :

    12345Finished

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (6 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    Got it ? Break means go out from current loop. It can also be applied on while...do and repeat...until. How about nested loop ? Break only applies on its begin...end block. Check out the program below :

    begin for i:=1 to 4 do begin for j:=1 to 5 do begin writeln(i,' ',j); if j=3 then break; end; writeln('Next i loop'); end; writeln('Finished !'); end.

    It yields :

    1 11 21 3Next i loop2 12 22 3Next i loop3 13 23 3Next i loop4 1

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (7 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    4 24 3Next i loopFinished !

    Another example :

    begin for i:=1 to 5 do begin for j:=1 to 3 do begin writeln(i,' ',j); end; if i=2 then break; end; writeln('Finished !'); end.

    It yields :

    1 11 21 32 12 22 3Finished !

    Break only does its function in its current scope (begin...end block) How about if I want to skip instead of quitting current loop ? Well, use Continue instead of Break. Replace all Break in previous examples with Continue and see what happens.

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (8 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    Extra !!!

    Here we are, have additional lessons :

    1. Random and randomize2. Halt3. ASCII characters

    Random and randomize

    All of them are used to generate random numbers. Random numbers are always used to simulate the reality, where certainty is hardly guaranteed. We are here not to discuss how to make it, but how to use these two commands.

    Randomize is used to start the random generator, so that it is only used at the first initialization, placed after the begin in the main block. It is enough to call it once, even though it may be called several times. Random is used to get the random number. Its parameter is the highest possible number that can be generated. Suppose : num:=random(50); It means that num will contain any integer number between 0 to 49. Look at next example :

    var

    i : byte;begin randomize; for i:=1 to 100 do write(random(30),' ');end.

    Let's remove the randomize. Run it for several times and note that when it runs, if you don't use randomize, the computer will result the same number. So, always use the randomize so that the computer generate quite a good random numbers.

    Halt

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (9 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 5

    Just stop and return to system. Usage : Halt; You may place it anywhere you want. If computer encounters the halt, it will stop the program execution and back to the operating system.

    ASCII characters

    There are 128 basic ASCII characters and 128 extended ASCII characters. Writing ASCII characters is as simple as using writeln; Example :

    writeln(#30); { Writing ASCII code 30 }

    Try changing 30 with other numbers between 0 to 255.

    That's all. We'll have a quiz. Well, it's not hard, actually, but it is harder than before. Bye for now !

    Where to go ?

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 4 about constantsTo Chapter 6 about procedures and functions

    file:///F|/Documents/Pascal_Doc/pas/pasl1004.html (10 of 10)8/3/2005 7:43:36

  • Pascal Tutorial - Chapter 6

    What are Procedures and Functions

    Hello ! Nice to meet you again ! How is the lessons ? It was a great quiz, wasn't it ? Well, time's getting more difficult to pass through. I've got a very busy semester, so that I may not even keep my promise in the Web........ Sorry ! But I keep moving on, don't worry !

    Contents :

    1. Simple syntaxes2. Scope3. Local variables and global variables4. Parameters (pass by value and pass by reference)5. Ignored return values6. Inter-procedure and/or functions call7. Nested syntax8. Recursive calls9. Inter-referenced procedures/functions

    10. Break down problems

    OK ! Let's start ! We know that Pascal is a structured language. It means that the problems is divided into steps and subproblems and then is coded in a structure. This division is made through procedures and functions. Well, what the hell are procedures and functions ? It is like a subprogram that has its own begin..end. It is useful when a part of program must be performed more than once in scattered parts of the program. May be it is a bit murky, but let's take a look on its syntax :

    Procedure procname;begin :

    { commands } :

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (1 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    :

    end;

    begin

    end.

    This is the simplest form of a procedure. (Functions are discussed later) As we can see that procedures are always placed ABOVE the main begin...end. Example :

    uses crt;

    procedure pause;begin writeln('Press any key when ready ...'); readkey;end;

    begin clrscr; writeln('ABC'); pause; { Make a call to procedure pause } writeln('Hey, let''s pause !'); pause; { Make a call to procedure pause } writeln('Pause again !'); pause; { Make a call to procedure pause }end.

    Run the previous example. Look at this example :

    uses crt;

    begin

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (2 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    clrscr; writeln('ABC'); writeln('Press any key when ready ...'); readkey;

    writeln('Hey, let''s pause !'); writeln('Press any key when ready ...'); readkey;

    writeln('Pause again !'); writeln('Press any key when ready ...'); readkey;end.

    It gives the same effect as the first example, isn't it ? Which is nicer ? Writing silly same phrases or efficiently using procedures. If you are normal guy, you would love the first example. It is clearer and cleaner. Easy to read. Especially the lines to be replaced with procedures are very long. Procedures, and functions too, make the codes healthier and easier to read. It makes life easier in debugging the program, too.

    Procedures could have its own variable, called local variable. The variable is only known inside the procedure. For example :

    procedure foo;var a : byte;begin a:=10; writeln(a);end;

    begin { main begin...end block } foo; a:=15; { This will be an error, since a is only known inside foo }

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (3 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    end.

    Global variable is a variable that is known throughout the program and its procedures or functions. Example :

    var

    b : byte;

    procedure foo;var a : byte;begin a:=10; b:=15; { This is legal }end;

    begin { main begin...end block } foo; a:=15; { This is illegal } b:=5; { This is perfectly legal }end.

    If a local variable is declared inside a procedure with the same name as the global variable, the global variable is overrided. For example :

    uses crt;var

    a : byte; { This is the global variable }

    procedure foo;var a : byte;begin

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (4 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    a:=15; writeln('foo is ',a);end;

    begin a:=10; writeln(a); foo; writeln(a);end.

    Functions are pretty much the same, except it has a return value. It just like mathematic functions. Syntax :

    function funcname : returntype;begin :

    { commands } :

    :

    end;

    begin

    end.

    Functions are also placed before the main begin...end. Example :

    uses crt;

    function yesno : boolean;var c : char;begin

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (5 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    write('Are you sure (Y/N) ? '); repeat c:=upcase(readkey); { Make it upcase letters } until (c='Y') or (c='N'); writeln(c); if c='Y' then yesno:=true else yesno:=false;end;

    var

    x : boolean; { Don't be tricked, this is a LOCAL variable of main block }begin clrscr; writeln('Discard all changes made'); x:=yesno; if x=true then writeln('Changes discarded !'); else writeln('Changes saved !');

    writeln('Quitting'); x:=yesno; if x then begin writeln('Process terminated !'); halt; end;

    writeln('Quit cancelled !'); writeln('Continuing process ...');end.

    Can you see a big difference between procedures and functions ? Use function if we want to get a return value. Suppose the yesno function. It returns true if user presses y and returns false if user presses n. Yes, yes, it is pretty complex. But, try to understand.

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (6 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    Or... try to understand this simple excerpt : (This is only the begin...end part. All above is the same as the previous one.)

    begin x:=yesno; if x then writeln('You answered "Yes"') else writeln('You answered "No"');end.

    In a well-structured program, we use global variables as minimal as possible and use the optimum amount of local variables. How can we ? Well, practice a lot ! Sometimes, we need some value to be known inside a procedure. In that case, we need parameters. We can put parameters just beside the procedure's or function's name, suppose :

    procedure myproc (a:integer; b:real);begin :

    :

    end;

    function abc (a,b : integer; c:byte) : longint;begin :

    :

    end;

    Let's see it in 'real life' !

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (7 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    uses crt;

    procedure makewin(x1,y1,x2,y2 : byte);var

    i,j : byte;begin { top } gotoxy(x1,y1); write(#201); for i:=x1+1 to x2-1 do write(#205); write(#187);

    { middle } for i:=y1+1 to y2-1 do begin gotoxy(x1,i); write(#186); for j:=x1+1 to x2-1 do write(' '); write(#186); end;

    { bottom } gotoxy(x1,y2); write(#200); for i:=x1+1 to x2-1 do write(#205); write(#188);end;

    begin makewin(1,1,30,8); makewin(10,10,60,18);end.

    Simple example above tell us about making a window in a coordinate (x1, y1) to (x2, y2). With this engine, we could make many windows with just entering coordinates and the SAME code. Parameters makes us easier to customize the procedures and functions. Let's see this example :

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (8 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    function factorial(n : byte):longint;var

    i : byte; result : longint;begin result:=1; for i:=1 to n do result:=result*i; factorial:=result;end;

    var

    x : byte;begin writeln('Enter a value : '); readln(x); writeln(x,'! is ',factorial(x));end.

    Those previous examples are widely used in programming life. Let's look at this :

    procedure foo(a : byte);begin writeln(a); {15} a:=10; writeln(a); {10}end;

    var

    x : byte;begin x:=15; writeln(x); {15}

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (9 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    foo(x); writeln(x); {Still 15}end.

    It outputs :

    15151015

    At first, x is 15, then passed to procedure foo as passing parameter a. Eventhough it is legal to modify a inside foo, the value of x is unaffected anyway. This type of passing method is called PASS BY VALUE. How about this :

    procedure foo(var a : byte); { See the difference?}begin writeln(a); {15} a:=10; writeln(a); {10}end;

    var

    x : byte;begin x:=15; writeln(x); {15} foo(x); writeln(x); {10}end.

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (10 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    It outputs :

    15151010

    If we add var before a as passing parameter, the value of x is changed whenever a is changed. This type of passing method is called PASS BY REFERENCE.

    We must pass by value if the parameters are not necessarily be changed in the procedure. If the parameters need changing and the change is important to be known by the caller, use pass by reference.

    In Borland Pascal 7.0, we could omit the return values of a function. In our examples so far, we use readkey, right ? Readkey is actually a function but a built-in one. Before version 7.0, we must take a return value of it (readkey), like this : c:=readkey;. But, from version 7.0, we could omit it by just calling readkey like this : readkey;

    You CAN call another procedure inside a procedure or function as long as the caller procedure/function lies below it. Example :

    procedure a;begin :

    :

    end;

    procedure b;begin :

    a; { legal }end;

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (11 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    begin :

    end.

    It is legal for procedure b to call procedure a. But procedure a can NEVER call procedure b. It is ILLEGAL. Function can call procedures, procedures can call functions, functions can also call other functions as long as the caller is below the target (the one which is invoked). So, you'd better arrange the procedures and functions you might have.

    If the if-structure and loop structures could nest each other, can procedures and functions nest each other ? YES, IT COULD ! Example :

    procedure e; { e cannot access a, b, c, and d }begin :

    end;procedure a; procedure b; begin c; {illegal} e; {legal} end; procedure c; begin b; {legal} e; {legal} end;begin :

    b; {legal} c; {legal} e; {legal}end;procedure d;

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (12 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    begin :

    b; {illegal} c; {illegal} a; {legal} e; {legal}end;

    begin :

    b; {illegal} c; {illegal} a; {legal} d; {legal} e; {legal}end.

    Procedure c can call procedure b since c is below b, but procedure b cannot call procedure c. Procedure a, whose begin..end block below procedure b and procedure c, can call procedure b and c. Procedure b and c cannot be access ed by procedure d and main block. So, nested procedure can only be accessed by their brothers/sisters (among the same level of nested procedure), and their parent (the procedure who endow them). Accesses between brothers follow the rule of normal procedure calling.

    Practice a lot !

    How about calling ourselves ? Well, IT IS PERFECTLY LEGAL too !! Example :

    procedure a;begin a;end;

    begin

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (13 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    a;end.

    But it will say error since it call itself ENDLESSLY. The method of calling oneselves is called RECURSIVE CALLS. In recursive calls, we must :

    1. Provide terminating conditions.2. Be extremely careful in coding.3. Not use too many recursive calls, say 50,000 times.

    If not, you could find these symptoms :

    1. Hang / stopped responding.2. Computer "auto-murmur".3. Beeping eratically.4. Auto-reboot.5. Auto-format (no...no ! Just kidding !)6. Other unexpected result

    Let's see a very good example of recursive calls : It's factorial. See the non-recursive method of factorial function above, then see this recursive version :

    function factorial (n:byte):factorial;begin if n

  • Pascal Tutorial - Chapter 6

    If x = 5,At first call, n = 5. Factorial:=5*factorial(4); => need second callSecond call, n = 4. Factorial:=4*factorial(3); => need third callThird call, n = 3. Factorial:=3*factorial(2); => need fourth callFourth call, n = 2. Factorial:=2*factorial(1); => need fifth callFifth call, n = 1. Factorial:=1; => inserted back to above so4th call becomes : Factorial:=2*1; (=2) => inserted back to above so3rd call becomes : Factorial:=3*2; (=6) => inserted back to above so2nd call becomes : Factorial:=4*6; (=24) => inserted back to above so1st call becomes : Factorial:=5*24; (=120)

    As you may see that factorial in recursive method is simpler than ever. Suppose you miswrite n-1 to n, the terminating condition would never be functional. So, it will loop forever ! Be careful !

    Well, we come to a quite advanced matter. It is sometimes used though. Inter-referenced calls. It means that 2 procedures or functions could call each other.

    procedure a;begin b; { illegal }end;

    procedure b;begin a;

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (15 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    end;

    As you may see, calling a from b is legal, but calling b from a is illegal. It sometimes necessary for a to call b and for b to call a. The real-life problem is like context-sensitive help. Sometimes the description, when it is pointed or clicked, it call the index. But also, the index has to call its description after a topic is picked. The solution is : FORWARD CALL. Example :

    procedure b; forward;

    procedure a;begin b; { now legal }end;

    procedure b;begin a;end;

    Use the statement forward to make b visible to a, so a can call b. It is more dangerous than recursive call. If you are not careful, you may find the same symptoms as recursive call did. What you must do is also the same as in the recursive call. Just beware : Calling procedures uses a part of memory called stack. Reciprocal calls wastes stacked much faster than recursive calls. If you run out of stack, your program would stuck.

    How could I break down complex problems ? How good your ability in breaking problems is actually depends on your experience in programming. But, I can only tell you this :

    1. Identify your problem correctly.Suppose you have to make a program to record employee data for a bank. What is it for ? Employee data for just an information or for salary statistics or what ?

    2. Separate one process from another.Suppose you do employee data for information. The processes are record it to

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (16 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    disk, edit data, delete data, sort data, or print and display data, or search data.3. List the solution steps of each process.

    Suppose you first do record data. You take input from keyboard and record it to disk. You ask if user wants to input again or not.

    4. List the data requirements.Employe data may require name, position, residence, office location, civil status, age, sex, years of service, and so on.

    5. Determine the output requirements.You may design the output like a list of employee data. It is useful for comparison reason. Or may be you would love to make it like an archive form for complete document. Or you ask the user and they can choose.

    6. Construct an algorithm to do the process.Suppose taking data from keyboard, may sound : input name, input age, input position, and so on. Then prepare file, record the data to disk, close the file. Ask user if they want to input some more. If they do, repeat the whole process, otherwise quit.

    7. Use your creativity to expand the input, process and output.Don't stick the model from input to output. You may add your creativity. Client may want the output format exactly the same as they wish. Perhaps you could give suggestions in arranging them, or perhaps if you think some data is important to display or print, go tell the client.

    8. Think of all other useful things to add in program.Suppose you want to add the feature of Auto-Correct, to minimize the human-error. You probably record some usual names, like Jim, Dave, and so on. If user types Dabe, for example, your program can give suggestion to change it to Dave. Yeah, somethings like that.

    9. Implement it, step by step.Don't let all dreams be dreams. Let it comes true.

    10. Combine all the programs to tackle the problem.All the module of each process should be gathered. You may want to generalize your input procedure to fit in each module to save energy and time. Combine them using menus. And don't forget to make finishing touches, to make the software looks great.

    Well, that's one of the complex problems. You may follow the guidelines. OK, that's all for today ! Have a good quiz ! =)

    Where to go ?

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (17 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 6

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 5 about loopingTo Chapter 7 about arrays

    file:///F|/Documents/Pascal_Doc/pas/pasl1005.html (18 of 18)8/3/2005 7:43:43

  • Pascal Tutorial - Chapter 7

    Mastering Array

    Hello ! Nice to meet you ! It seems you are cleverer day by day. You are even be able to write simple games ! I have a little problem on my health recently, so I have to get some good rest. Topics that will be discussed this time are :

    1. What is an array.2. Declarations.3. Using arrays.4. Two-dimensional array.5. Multi-dimensional array.6. Special case of array.

    Let's begin !

    What is an array exactly ? Well it is like a variable that is able to store a bunch of data. Think about drawers. Drawers have several latches, don't they ? Each latch could keep things safe. Eventhough they have so many latches and store things, they are called drawers. Confused ? Let's look at the declaration :

    var

    arrayname : array [x..y] of vartype;

    Example :

    var

    ourdata : array[1..100] of byte; myarray : array[5..25] of char;

    Yes, yes, name it whatever you want. Array declarations are located inside the var block. You can declare arrays as global variable or local variable, just whenever you want it. How to use it ? Suppose, I have an array :

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (1 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 7

    var

    x : array[1..30] of byte;

    It means that x has 30 elements ranging from 1 to 30. Each element can be accessed individually, not affecting others. Suppose I want to access the first element, it would be :

    x[1]:=10; { Suppose I want to fill the first element with 10 }

    Then, I would like to access the second element :

    x[2]:=15;

    If you check the first element, it is still 10. Even I have assigned the second element with 15, the first one still retain its originality. Check out this simple program to gain better understanding :

    var

    a : array[1..10] of byte;

    begin a[1]:=10; a[2]:=15; a[3]:=a[1]+a[2]; writeln(a[1]); writeln(a[2]); writeln(a[3]);end.

    As you can see that the variable a could store multiple values. Each element could be accessed without interfering others.

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (2 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 7

    In what case the array contribute to the applications in real-life ? Suppose you have a list of names. You would probably prefer to have an array of names instead of declaring each variable names. Suppose : It would be nicer to store 10 names with an array like this :

    var

    names : array[1..10] of string;

    rather than having each variables like this :

    var

    name1, name2, name3, name4, name5, name6, name7, name8, name9, name10 : string;

    Array makes us easier in writing the contents. Writing all the names with an array names above, would be :

    for i:=1 to 10 do writeln(names[i]);

    You would love doing that rather than writing writeln statements with 10 variables intact. It is much easier and simpler.

    What about if I have a table of x and y, could I access it with array too ? Yes ! But, you will need a two-dimensional array. It is the same, but the declaration is like this :

    var

    table : array[1..5, 1..3] of byte;

    That table is 5x3 in size. How to access it ? Well, like this :

    table[5,3]:=5;

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (3 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 7

    table[1,2]:=4; table[4,1]:=table[1,2]*table[5,3];

    Yes, it is pretty much the same. Well, array helps you make spreadsheets, just like Lotus 1-2-3 or Excel.

    How about the three-dimensional table or more ? It also the same. Look at the declaration :

    var

    table3d : array [1..5, 1..4, 1..6] of byte;

    Accessing it is all the same :

    table3d[3,4,5]:=6;

    And so on. You may extend it to 4-D array, like :

    var

    table4d : array[1..2, 1..3, 1..4, 1..5] of byte;

    Accessing it is analogue to the previous examples. 5-D array, or even 100-D array is just the same in concept.

    Here are the special case of array in Pascal : You can declare array like this :

    x : array[3..40] of integer; idx : array['A'..'Z'] of string; a : array['a'..'z'] of byte; n : array[byte] of integer; { The same as array[0..255] of integer; }

    Or even like this :

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (4 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 7

    schedule : array[Monday..Saturday] of string; carprice : array[Honda..Suzuki] of longint;

    These types of array will be discussed in depth in chapter 10.

    Accessing them is just the same :

    x[3]:=4; x[1]:=5; {Illegal} idx['D']:='Dave'; idx[1]:='XX'; {Illegal} a['a']:=65; n[0]:=1; n[255]:=10; n[5]:=5; schedule[Monday]:='Go meet clients at 10am'; carprice[Honda]:=15000; {US$}

    Well, well ! Got to practise a lot. Accessing array idx and a with loop is similar. Suppose c is a char variable :

    for c:='A' to 'Z' do idx[c]:=''; for c:='a' to 'z' do a[c]:=random(100);

    This kind of array, for me, is seldom used. The more usual ones are the array of schedule and carprice above. They use enumeration types. This will be discussed in chapter 10.

    OK, that's all for this time !

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (5 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 7

    Where to go ?

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 6 about procedures and functionsTo Chapter 8 about processing strings

    file:///F|/Documents/Pascal_Doc/pas/pasl1006.html (6 of 6)8/3/2005 7:43:47

  • Pascal Tutorial - Chapter 8

    Dancing with Strings

    Hi ! We meet again ! Now, I would like to discuss about strings in depth. How are you doing ? Well, I'm having health problem this day and I need a rest. I am still able to write this to you. Cheer ! Topics discussed this time are :

    1. String as array of char2. Limited length string3. String manipulation commands :Length, Copy, Pos, Val, Str, Concat, Insert, Delete, Fillchar

    4. String as a pointer of characters (PChar), introductionLet's begin !

    Actually, string is an array of characters. So, suppose s is a string. s[1] is equal to the first character of s. s[2] is the second character, and so on. Look at this :

    var

    s : string;begin s:='Hello, dear'; writeln(s); s[1]:='J'; { Replace the first character with J } s[5]:='y'; { Replace the fifth character with y } writeln(s); { Jelly, dear } writeln('The length of s is ',ord(s[0]));end.

    Zeroth character is the character form of the length of that string. So, ord(s[0]) denotes the actual length of s. You may replace it with length(s) which gives the same effect.

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (1 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 8

    Normally, strings would hold 80 characters in maximum. Suppose you would have a set of strings that is about 10 characters long. Declaring each as normal string would be a waste of space. Pascal provides facility to limit the string length. If you would like to have a string that has maximum limit of 10 characters, you would write :

    var

    s : string[10];

    Pascal also provides routines to manipulate string :

    1. Length : return string length.Syntax : length(s)Example : n:=length(s);Suppose s:='Who are you ?'; n would be 13.

    2. Copy : get an excerpt from a string.Syntax : copy(s,from,howmuch)Example : st:=copy(s,5,3);Get an excerpt of 3 characters from s, beginning from the 5th character.Suppose s:='Who are you ?'; st will be 'are'.Note that if index from is greater than the length of s, st would be empty, example :st:=copy(s,15,4); { empty string }If howmuch exceed the end of the string s, it returns the remainder of the string, example :st:=copy(s,9,10); st would be equal to 'you ?'

    3. Pos : get the position of a substring from a string.Syntax : Pos(substr,s)Example : n:=pos('are','Who are you ?');{ n:=5; }If the substring is not found, it returns 0.

    4. Val : converts strings to numeric.Syntax : val(strvar,numvar,errorcode)strvar is a string variable to be converted, numvar is any numeric variable either integer or real, and errorcode is an integer variable that holds the error code. If errorcode is 0, conversion success. Otherwise, it points at the position of strvar that cause failure. Example :

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (2 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 8

    var

    s : string; e : integer; r : real;

    begin write('Enter a number : '); readln(s); val(s,r,e); if e0 then writeln('Error at position : ',e); else writeln('That was : ',r:4:3);end.

    5. Str : converts numeric into strings.Syntax : str(numvar,strvar)Example :

    var

    s : string; i : integer;begin write('Input an integer : '); readln(i); str(i,s); writeln('That was : ',s);end.

    Note that if you deal with real, you may format it before you convert it into strings. Suppose r is a real variable, s can be like this :

    str(r:4:3,s);s consists of 4 digits before the decimal point of r, and 3 digits after the decimal point. Example :

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (3 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 8

    var

    s : string; r : real;begin write('Input a real : '); readln(r); str(r:4:3,s); writeln('That was : ',s);end.

    6. Concat : Concatenates two or more stringsSyntax : concat(s1,s2,...,sn)Example : st:=concat(s1,s2);If s1='ABC' and s2='DEF', st would be 'ABCDEF'st:=concat('Borland ','Pascal ','ver. ','7.0'); Would be 'Borland Pascal ver. 7.0'You may put as many parameters to concat as possible. If the resulting string length is more than 255, it will be truncated to 255.Concat is the same if we use plus sign (+). For example :st:=concat('ABC','DEF'); is the same as st:='ABC'+'DEF';

    7. Insert : Insert a string inside another string from indexth characterSyntax : insert(source,target,index)Example :

    var

    s1, s2 : string;begin s1:='not '; s2:='I do love you'; insert(s1,s2,6); writeln(s2); { I do not love you }end.

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (4 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 8

    If the result string length is more than 255, it will be truncated into 255 as well.

    8. Delete : Deletes n characters from string s starting from index i.Syntax : delete(s,i,n);If index i is greater than length of s, s is unchanged. If n specifies more characters than remain (starting from i), the remainder of the string is deleted. Example :

    var

    s : string;begin s:='I am not responsible for that !'; delete(s,6,3); writeln(s); { I am responsible for that }end.

    9. Fillchar : fill string s with character c until s is n-1 char long.Syntax : fillchar(s,n,c);Beware : s[0] is overrided, so don't forget to add s[0]:=chr(n-1); to normalize it.

    var

    s : string;begin fillchar(s,51,'='); s[0]:=chr(50);end.

    Actually, those procedures or functions can be read from Pascal's help. So, refer to Borland Pascal help if you want working examples. You can even make your own string functions. If you don't understand, e-mail me.

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (5 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 8

    As Borland Pascal 7.0 arrives, we know that C style string is adopted in. In C, we view strings either as an array of characters or a pointer of characters. Pointer will be discussed in second lesson. The main reason is that Pascal can not maintain strings larger than 255. Then a new type of string is employed : PChar, a pointer of character.

    Pascal string consists of : one byte for its length then the contents. In PChar, just like C, we don't recognize the length. All we know is when the string stops -- that is when we encounter ASCII 0 (NULL). That null stop style makes the C style of string called NULL TERMINATED STRING.

    All string manipulation routines for PChar are adopted from C. If you would like to know each one of it, you should learn C, where it came from. Nevertheless, you could even learn it in Borland Pascal help too.The details of pointers and this type of string could be found in my second lesson of Pascal.

    You could compare two strings just like numbers, too ! Suppose s1 and s2 are strings, you could do like this : if s1 < s2 then .... (and so on ...)That's all for this time.

    Where to go ?

    Back to main pageBack to Pascal Tutorial Lesson 1 contentsTo the quizBack to Chapter 7 about arraysTo Chapter 9 about records

    file:///F|/Documents/Pascal_Doc/pas/pasl1007.html (6 of 6)8/3/2005 7:43:53

  • Pascal Tutorial - Chapter 9

    Best Records

    Hello ! We meet again ! How are you ? Good ? Thank God ! Ready to take this lesson ? Good ! Topics discussed this time are :

    1. What is records2. Declarations3. How to use it (with...do)4. Nested records5. Conditional records6. Extras : Sorting methods ! (Bubble, Shell, and Quick)

    Let's begin !

    Like an array, record is just grouping various data under one name. However array can only store ONE type of data, but record can store ALL kind of data, including arrays.

    How could we declare a record ? Actually, record is a customized kind of data type. So, I hereby want to introduce you the type part of Pascal program. The type part is placed BEFORE the var part. Let's look at the outline of somewhat-complex-Pascal-program-structure :

    program programname;uses units1, units2, ...;type name = variabletype; :

    : (type declarations)var

    (variable declarations)

    :

    :

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (1 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    (procedures and functions):

    :

    begin (main begin...end block) :

    :

    end.

    You can declare variable type anywhere, but normally, before variable declaration. Here is one example to declare a record :

    type TEmployee = record name : string[25]; address : string[40]; age : byte; position : string[10]; commision : real; end;

    var

    x : TEmployee;

    Record will be no use after its declaration if there are no variable using it. So, you can use the declaration if you have a variable of that kind of data. In this case, x. So, let's look at the main begin...end block :

    begin x.name := 'Paul Doherty'; x.address := '11th Kingston Avenue'; x.age := 35;

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (2 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    x.position := 'Salesman'; x.commision := 0.10;end.

    Through x, all accesses are available. Beware that : TEmployee.name is NOT the way to access name field.

    Each data stored inside a record is called FIELDS. So, the TEmployee has fields of name, address, age, position, and commision.

    Sometime, if we have so many fields inside a record, we find it is bothersome to write the variable, like the example above : so many x has to be written. We may want to simplify it. The example above (the main begin..end block) can be written as follows :

    begin with x do begin name := 'Paul Doherty'; address := '11th Kingston Avenue'; age := 35; position := 'Salesman'; commision := 0.10; end;end.

    Suppose you have a variable called name, how can Pascal distinct it from the record fields of name ? Within with...do statement, the record field overrides. If you want to assign the name variable, not the one which is the field of x, do it outside of with...do block.

    You can use array of records. Suppose you have declared the TEmployee record tag. Now you want to declare an array of it. It's simple :

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (3 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    var

    MyEmployee : array[1..100] of TEmployee;

    Just like declaring normal arrays. How to access it ? Suppose I access the first element :

    begin MyEmployee[1].name := 'Paul Doherty'; MyEmployee[1].address := '11th Kingston Avenue'; MyEmployee[1].age := 35; MyEmployee[1].position := 'Salesman'; MyEmployee[1].commision := 0.10;end.

    With with...do it's all the same :

    begin with MyEmployee[1] do begin name := 'Paul Doherty'; address := '11th Kingston Avenue'; age := 35; position := 'Salesman'; commision := 0.10; end;end.

    Can we do nested record as looping and conditional do ? Good question ! It IS perfectly legal. But you may do it like this :

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (4 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    type TCommision = record sales : real; production : real; absence : real; end; TEmployee = record name : string[25]; address : string[40]; age : byte; position : string[10]; commision : TCommision; end;

    In that example, the field commision of TEmployee record tag is a record of TCommision. How to access the sales field of commision ? Easy ! Suppose you have declared x as a variable of TEmployee : x.commision.sales:=0.5; Just add another period after commision then type sales, that's it ! Using arrays are pretty much the same ! MyEmployee[1].commision.sales:=0.3;

    You may nest records more than 2 steps. To accomplish such task you may use analogies to the previous example. To access them is quite the same, just type down the period and subfield name and so on. The deeper you nest, the longer you type.

    You may use with...do block inside another with...do block to access nested records. Go on, try it !

    One special caution should be taken :Pascal give a special gift that may not even exist in other programming languages : CONDITIONAL RECORDS. What is conditional records exactly ? Conditional records are record with a variable length depending on the contents of a field. That field whose contents become so important is called pivot field. Let's look at this :

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (5 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    type TEmployee = record Name : string[20]; Age : byte; case department:byte of 0: (sales : longint); 1: (product : integer); end;

    TEmployee has the field of name, age, and department. Department is a byte field. If the department is 0, then the TEmployee contains sales field as the next field. Or else, in this case 1, it has product field as the next one. The usage is quite rare though. Yet, this is very useful indeed.

    Need to know :You have already known division in Pascal. How can we get the remainder ? Well, use mod :

    x := n mod 13; { x is the remainder of n after divided by 13 }

    EXTRA !

    As the lesson in this chapter is quite short, I decided to give you some extras. That is sorting methods. Three of which I'm going to tell you is the extreme :

    1. Bubble Sort (Well-known of its simplicity but very slow)2. Quick Sort (Well-known of its speed but quite complex)3. Shell Sort (Quite fast but not too complex)

    The simplest but quite powerful sorting methods among all is bubble sort. It is very easy to implement. The idea is bubbling up the desired data into sorted order. Suppose we want to sort the data ascendingly, earlier or smaller data will come up gradually. The main layout algorithm for this, is just like this :

    for i:=1 to NumberOfData-1 do

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (6 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    for j:=i+1 to NumberOfData do if Data[i]>Data[j] then swap Data[i] with Data[j];

    That's all ! Very simple. If you want to sort descendingly, replace the '>' with '

  • Pascal Tutorial - Chapter 9

    Data[i].name:=Data[j].name; Data[i].address:=Data[j].address;

    Data[j].name:=t.name; Data[j].address:=t.address; end;

    Yup ! Simple, eh ? All sorting methods need swapping and the swapping is done in the same way.

    The algorithm :(If you are curious, you may read through. If you are as just practical as me, you may skip this part without losing lesson details.)

    The idea of bubble sort is just comparing all the data. The first data is compared to the second, to the third, and so on until the end of the data. Then the second data compared to the third, to the fourth, so on. Then the third data to the fourth and so on ... and so on.

    Why it is called as the Bubble sort. It is because that the comparison and the swapping make the desired data to gradually come up like a bubble. Example : Suppose we have data like this

    5 3 8 4 1 7 6 2 (unsorted)

    Follow the algorithm -- i.e. comparing the first and the second data : 5 and 3. 5 is greater than 3, hence it must be swapped out

    3 5 8 4 1 7 6 2 (1st step)

    Then the first and the third. Since 3 is smaller than 8, no swapping is necessary. Then the first and the fourth : No swapping either. The first and the fifth -- since 1 is smaller than 3, it must be swapped :

    1 5 8 4 3 7 6 2 (4th step)

    And so on, till the end of data, the sequence remains the same. Then

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (8 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    the second with the third -- no changes this time. The second with the fourth. Change must be done :

    1 4 8 5 3 7 6 2then becomes :

    1 3 8 5 4 7 6 2

    And so on :

    1 2 8 5 4 7 6 31 2 5 8 4 7 6 31 2 4 8 5 7 6 31 2 3 8 5 7 6 41 2 3 5 8 7 6 41 2 3 4 8 7 6 51 2 3 4 7 8 6 51 2 3 4 6 8 7 51 2 3 4 5 8 7 61 2 3 4 5 7 8 61 2 3 4 5 6 8 7

    Finally, sorted : 1 2 3 4 5 6 7 8

    You see that smaller data comes up like bubble and bigger data sank down gradually, as you may note the 8. That's why this method is called bubble sort.

    Before we go to quick sort, let's discuss shell sort. Well, shell sort is a kind of exchange sort, actually, but it is optimized for speed. This algorithm is invented by Donald Shell, long long ago. His algorithm was named according to his name.

    The idea is comparing two datas in a quite distance in an array. Suppose, I have 8 data. First I compare the first with the fifth, and so on. Look at this excerpt :

    for gap:=(NumberOfData div 2) downto 1 do for i:=1 to NumberOfData-gap do if Data[i]>Data[i+gap] then

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (9 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    swap Data[i] with Data[i+gap];

    It is quite similar to bubble sort, right ? Actually, it IS quite speedy and powerful. Let's track it down ! Suppose we have 8 data, then gap is initially 4 (8 div 2 is equal to 4, right ?). Variable i moves from 1 to 4. It start comparing the first with the fifth, the second with the sixth, the third with the seventh, and the fourth with the eighth. As usual, if there are any mismatches in order, it swaps around. Then the gap reduces from 4 to 3. Again, i moves from 1 to 5, comparing it. And so on.

    (You may skip this if you want to)

    Let's look at our first scrambled data in our bubble sort example :At first, gap is 4. 5 3 8 4 1 7 6 21st comparison : ^ ^ (mismatch order, swap) 1 3 8 4 5 7 6 22nd comparison : ^ ^ (good order, no swap)3rd comparison : ^ ^ (mismatch order, swap) 1 3 6 4 5 7 8 24th comparison : ^ ^ (mismatch order, swap) 1 3 6 2 5 7 8 4 ----> Then the gap is 3.5th comparison : ^ ^ (good order, no swap)6th comparison : ^ ^ (good order, no swap)7th comparison : ^ ^ (good order, no swap)8th comparison : ^ ^ (good order, no swap)

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (10 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    9th comparison : ^ ^ (mismatch order, swap) 1 3 6 2 4 7 8 5 ----> Then the gap is 2.10th comparison : ^ ^ (good order, no swap)11th comparison : ^ ^ (mismatch order, swap) 1 2 6 3 4 7 8 512th comparison : ^ ^ (mismatch order, swap) 1 2 4 3 6 7 8 513th comparison : ^ ^ (good order, no swap)14th comparison : ^ ^ (good order, no swap)15th comparison : ^ ^ (mismatch order, swap) 1 2 4 3 6 5 8 7 ----> Then the gap is 1.16th comparison : ^ ^ (good order, no swap)17th comparison : ^ ^ (good order, no swap)18th comparison : ^ ^ (mismatch order, swap) 1 2 3 4 6 5 8 719th comparison : ^ ^ (good order, no swap)20th comparison : ^ ^ (mismatch order, swap) 1 2 3 4 5 6 8 721th comparison : ^ ^ (good order, no swap)22th comparison : ^ ^ (mismatch order, swap)

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (11 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    1 2 3 4 5 6 7 8

    Finished and completely sorted. Easy, no ? Much faster than bubble sort.

    Let's look at the fasted sort method in the world in general data : quick sort. It is invented by E. Hoare. It uses recursive method exhaustively. The idea is simple actually. Divide the data into two equal parts. Let the middle data be the pivot point. Gather all data below the pivot into the left side of the pivot, and the greater on the right. Let's see how is the partings. The equal parts is now unequal in size, since there are possibilities that one side is bigger than others. Each part is treated the same way, sorted with the same way. But now, the left side is choosing its new pivot and have two parts again. It is also done to the right side.

    Enough about lengthy theory. I'll bet you are yawning now. Let's look at the inside : Suppose Data is a global array of byte.

    procedure qsort(lower, upper : byte) var

    left, right, pivot : byte; begin pivot:=Data[(lower+upper) div 2]; left:=lower; right:=upper;

    while left pivot do right:=right-1;{ Parting for right} if left

  • Pascal Tutorial - Chapter 9

    end; end; if right>lower then qsort(lower,right); { Sort the LEFT part } if upper>left then qsort(left ,upper); { Sort the RIGHT part } end;

    Usage : qsort(1,NumberOfData);

    (This is quite technical, you may skip this without losing the details of the lesson. You may read this through to know how qsort works.)

    At first we assume that the center point of data contains the correct order in the sequence. Thus, we make this as a pivot point. At the excerpt above, we have two pointers, named left and right, pointing the first data and the last one. Then we seek at the left hand side first for mismatch data. In order to swap the data around, we must seek its pair on the right hand side first. It is NOT the pivot we change, but the mismatches data so that they place the correct parting.

    You may wonder whether it is safe to do that assumption. Yes, IT IS. Why ? It is because the search for mismatch data is not limited from edge to the pivot, but it may overlap the center. Thus, the parting is not equal any longer. The parting is decided when the left marker and the right marker crosses. It means that the comparison is done throughout the data.

    When the marker crosses, the left marker is at the right hand side of the right marker so that RIGHT parting made of left marker and the upper bound of the data. The LEFT parting is made from lower bound to right marker. Then each parting is sorted again, using recursive method.

    The two ifs before end; makes sure that the lower limit of the parameter is always less than the upper limit. This also as a quitting conditions to avoid endless repetitive recursive call.

    Let's look at our first scrambled data :

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (13 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    5 3 8 4 1 7 6 2Current position : | | |left : at first data (5)---+ | |right : at last data (2)---------+-------+pivot : at fourth data(4)---------+ Remember that (1+8) div 2 = 4

    Do the left parting :5 > 4 --> mismatch the order, left marker stays

    Do the right parting :2 < 4 --> mismatch the order, right marker stays

    Since left marker and right marker haven't crossed yet, it is legal to swapboth data, so it became : 2 3 8 4 1 7 6 5Left marker moves to the second data (3), right marker to the seventh (6).

    Since left marker and right marker haven't crossed yet, the main loop goes.

    Do the left parting :3 < 4 --> legal, continue.8 >= 4 --> mismatch, left marker stays.

    Do the right parting :6 > 4 --> legal, continue.7 > 4 --> legal, continue.1 mismatch, right marker stays.

    Since left marker and right marker haven't crossed yet, it is legal to swap

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (14 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    both data, so it became : 2 3 1 4 8 7 6 5Left marker moves to the fourth data (4), right marker moves to the fourthdata, too. It hasn't crossed yet, so it continues.

    Left marker stops the left parting because 4 is not less than 4, so doesthe right marker. It swaps itself, so nothing is changed. Then left markeradvances to the fifth data, right marker to third data.

    Left parting is made by lower bound and right marker (data no 1 to 3) andright one is made by left marker and upper bound (data no 5 to 8)

    This goes to recursive process. Let's look at the left parting first. 2 3 1 ...

    left marker = 2 right marker = 1 pivot = 3 { (1+3) div 2 = 2, Data[2]=3 }

    Do the left parting : 2 < 3 --> legal, continue 3 >= 3 --> mismatch, left marker stops Do the right parting : 1 mismatch, right marker stops Because left and right marker haven't crossed, it is legal to swap data. So, it becomes : 2 1 3 ... (pivot is still=3)

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (15 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    Left marker advances to 3, and right marker to 1. It crossed. The left parting would be from data no 1 to 2 and the right parting would consist only 3.

    We look into the left parting first: 2 1 ...

    left marker = 2 right marker = 1 pivot = 2 { (1+2) div 2 = 1, Data[1] = 2 }

    Do the left parting : 2 >= 2 --> mismatch, left marker stays

    Do the right parting : 1 mismatch, right marker stays.

    Swap the data so we have 1 2 ..., now we advance both left and right marker. It crossed. We have just 1 as the left parting and 2 as the right parting. So, we have nothing to sort. We then exit the recursive calls and revert to: 1 2 3 ..., sorted form of the original left parting.

    Then we look into the original right parting: ... 8 7 6 5

    left marker = 8 (position 5) right marker = 5 (position 8) pivot = 7 { (5+8) div 2 = 6, Data

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (16 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    [6] = 7 }

    Do the left parting: 8 >= 7 --> mismatch, left marker stops

    Do the right parting: 5 mismatch, right marker stops

    Data then swapped: ... 5 7 6 8 Then the left marker points at 7, the right marker points at 6 because we advance the pointer. The pivot is still 7.

    Do the left parting: 7 >= 7 --> mismatch, left marker stops

    Do the right parting: 6 mismatch, right marker stops.

    Then we swap the data: ... 5 6 7 8 And advance the pointers so that left marker points to 7 (again) and right marker points at 6 (again) :-) Pivot is still 7.

    The pointers are crossed, so we have another left parting from 5 to 6 and the right parting from 7 to 8. However, the data is already sorted, so the parting is essentially does nothing but to return from recursive calls.

    All data sorted after quitting the recursive calls : 1 2 3 4 5 6 7 8

    file:///F|/Documents/Pascal_Doc/pas/pasl1008.html (17 of 18)8/3/2005 7:43:57

  • Pascal Tutorial - Chapter 9

    Phew, quite a lengthy explanation, huh ? Looks like you need a break by now. OK, see you next time !

    Where to go ?

    Back to main pageBack to Pascal Tutorial L