60
A Turbo Pascal Reference The following is a list of Turbo Pascal procedures. Append GetintVec Release Arc GetLineSettings RenameSetDate Assign GetMem ResetSetFAttr AssignCrt GetPalette RestoreCrtMode Bar GetTextSettings Rewrite Bar 3D Get Time RmDir BlockRead GetVerify RunError BlockWrite GetViewSettings Sector ChOir GotoXY Seek Circle Halt SetActivePage Clear Device High Video SetAllPalette ClearViewPort Inc SetAspectRatio Close InitGraph SetBkColor CloseGraph Insert SetCBreak ClrEol Ins Line SetColor ClrScr Intr SetFillPattern Dec Keep SetFillStyle Delay Line SetFTime Delete LineRel SetGraphMode Del Line Line To SetintVec DetectGraph LowVideo SetLineStyle Dispose Mark SetPalette Ellipse MkDir SetRGBPalette Erase Move SetTextBuf Exec Move To SetTextJustify Exit New SetTextStyle Fail NormVideo Set Time Fill Char No Sound SetUserCharSize FillEllipse Out Text SetVerify Fill Poly OutTextXY SetViewPort FindFirst OvrClrBuf SetVisualPage FindNext Ovrinit SetWriteMode FloodFill OvrinitEMS Str Flush OvrSetBuf SwapVectors FreeMem OvrSetRetry TextBackground FSplit PackTime Text Color 314 Mastering Pascal

A Turbo Pascal Reference - Springer978-1-349-14770-0/1.pdf · Eof (typed) IOResult Sqr Eoln KeyPressed Sqrt Exp Length SSeg FExpand Lo Succ FilePos MaxAvail Swap FileSize MernA vail

  • Upload
    vanngoc

  • View
    225

  • Download
    1

Embed Size (px)

Citation preview

A Turbo Pascal Reference

The following is a list of Turbo Pascal procedures.

Append GetintVec Release Arc GetLineSettings RenameSetDate Assign GetMem ResetSetFAttr AssignCrt GetPalette RestoreCrtMode Bar GetTextSettings Rewrite Bar 3D Get Time RmDir BlockRead GetVerify RunError BlockWrite GetViewSettings Sector ChOir GotoXY Seek Circle Halt SetActivePage Clear Device High Video SetAllPalette ClearViewPort Inc SetAspectRatio Close InitGraph SetBkColor CloseGraph Insert SetCBreak ClrEol Ins Line SetColor ClrScr Intr SetFillPattern Dec Keep SetFillStyle Delay Line SetFTime Delete LineRel SetGraphMode Del Line Line To SetintVec DetectGraph LowVideo SetLineStyle Dispose Mark SetPalette Ellipse MkDir SetRGBPalette Erase Move SetTextBuf Exec Move To SetTextJustify Exit New SetTextStyle Fail NormVideo Set Time Fill Char No Sound SetUserCharSize

FillEllipse Out Text SetVerify

Fill Poly OutTextXY SetViewPort FindFirst OvrClrBuf SetVisualPage FindNext Ovrinit SetWriteMode FloodFill OvrinitEMS Str Flush OvrSetBuf SwapVectors FreeMem OvrSetRetry TextBackground

FSplit PackTime Text Color

314 Mastering Pascal

GetArcCoords PieSlice TextMode GetAspectRatio Put Image Truncate GetCBreak PutPixel UnPackTime Get Date Randomize Val GetDir Read (text) Window GetFAttr Read (typed) Write (text) GetFillSettings ReadLn Write (typed) GetFTime Rectangle WriteLn Get Image

The following is a list of Turbo Pascal functions.

Abs GetGraphMode ParamStr Addr GetMaxMode Pi ArcTan GetMaxX Pos Chr GetMaxY Pred Con cat GetModeName Ptr Copy GetPaletteSize Random Cos Get Pixel ReadKey Cseg Get X Round DiskFree GetY SeekEof DiskSize GraphErrorMsg SeekEoln DosexitCode GraphResult Seg DosVersion Hi SetAspectRatio Dseg ImageSize Sin EnvCount InstallUserDriver SizeOf EnvStr InstallUserFont Sound Eof (text) Int SPtr Eof (typed) IOResult Sqr Eoln KeyPressed Sqrt Exp Length SSeg FExpand Lo Succ FilePos MaxAvail Swap FileSize MernA vail TextHeight Frac MsDos Text Width FSearch Odd Trunc GetBkColor Ofs TypeOf GetColor Ord UpCase GetDefaultPalette OvrGetBuf WhereX GetDriverName OvrGetRetry WhereY GetEnv ParamCount

Turbo Pascal accesses some standard procedures and functions through units, which are libraries of precompiled modules. For example, the Crt unit con­tains routines which access the text display. To use a unit the uses keyword

Pascal reference 315

must be included in a statement near the top of the program. For example, to use the clrscr function:

program test;

uses crt;

begin clrscr; ( * clears the screen *) textcolor(RED); textbackground(YELLOW); writeln ('Hello');

end.

The listing of modules in the crt unit is:

AssignCrt Ins Line Text Background ClrEol KeyPressed TextColor ClrScr LowVideo TextMode Delay NormVideo WhereX Del Line No Sound WhereY GotoXY ReadKey Window High Video Sound

The listing of modules in the system unit is:

Abs GetDir ReadLn Addr GetMem Release Append Halt Rename ArcTan Hi Reset Assign Inc Rewrite BlockRead Insert RmDir BlockWrite Int Round ChOir IOResult RunError Chr Length Seek Close Ln SeekEof Con cat Lo SeekEoln Copy Mark Seg Cos MaxAvail SetTextBuf CSeg MernA vail Sin Dec MkDir SizeOf Delete Move Sptr Dispose New Sqr DSeg Odd Sqrt Eof (text) Ofs Sseg Eof (typed) Ord Str Eoln ParamCount Succ

316 Mastering Pascal

Erase ParamStr Swap Exit Pi Trunc Exp Pos Truncate FilePos Fred UpCase FileSize Ptr Val FillChar Random Write (text) Flush Randomize Write (typed) Frac Read (text) WriteLn FreeMem Read (typed)

The listing of modules in the dos unit is:

DiskFree Fsplit MsDos DiskSize GetCBreak PackTime DosExitCode Get Date SetCBreak DosVersion GetEnv Set Date EnvCount GetFAttr SetFAttr EnvStr GetFTime SetFTime Exec Get!ntVec Set!ntVec Fexpand Get Time Set Time FindFirst GetVerify SetVerify FindNext Intr SwapVectors Fsearch Keep UnpackTime

The listing of modules in the graph unit is:

Arc GetMaxY PutPixel Bar GetModeName Rectangle Bar 3D GetModeRange RegisterBGidriver Circle GetPalette RegisterBGifont ClearDevice GetPaletteSize RestoreCrtMode ClearViewPort Get Pixel Sector CloseGraph Get Text Settings SetActivePage DetectGraph GetViewSettings SetAllPalette Drawpoly Get X SetAspectRatio Ellipse GetY SetBkColor FillEllipse GraphDefaults SetColor Fill Poly GraphErrorMsg SetFillPattern FloodFill GraphResult SetFillStyle GetArcCoords ImageSize SetGraphBufSize GetAspectRatio InitGraph SetGraphMode GetBkColor InstallUserDriver SetLineStyle GetColor InstallUserFont Set Palette GetDefaultPalette Line SetRGBPalette GetDriverName LineRel SetTextJustify

Pascal reference 317

GetFillPattern Line To Set Text Style GetFillSettings MoveRel SetUserCharSize GetGraphMode Move To SetViewPort Get Image Out Text SetVisualPage GetLineSettings OutTextXY SetWriteMode GetMaxColor PieSlice TextHeight GetMaxMode Put Image TextWidth GetMaxX

The following is a quick reference to commonly used functions.

Abs

ArcTan

Chr

Concat

Copy

Cos

DiskFree

Disk Size

DosVersion

Eof

function Abs(x) : (Same type as parameter)

function ArcTan(x : real) real;

function Chr(x Byte) Char;

function Concat(sl [, s2, ... , sn): string): string;

function Copy(s : string; index : Integer;count Integer) : string;

function Cos(x : real) real;

function DiskFree( Drive: Byte) : Longint;

function DiskSize( Drive: Byte) : Longint;

function DosVersion : Word;

function Eof(var f) : Boolean;

318 Mastering Pascal

Returns absolute value

Returns the arctangent of the argument. Turbo Pascal does not have a Tan function, but tangents can be calculated using the expression Sin(x) I Cos(x)

Returns a character with a specified ordinal nwnber

Concatenates a sequence of strings

Returns a substring of a string

Returns the cosine of the argument.

Returns the nwnber of free bytes of a specified disk drive. Unit name Dos.

Returns the total size in bytes of a specified disk drive.

Returns the DOS version nwnber. The low byte of the result is the major version nwnber, and the high byte is the minor version nwnber. Unit name Do s.

Returns the end-of-file status of a typed or untyped file.

Eoln

Exp

File

FileSize

Frac

Fsearch

Int

Key Pressed

Length

MaxAvail

MernA vail

MsDos

Odd

function Eoln [ (var f : text) ] : Boolean;

function Exp(x : real) : real;

function FilePos(var f) Longint;

function FileSize(var f) : Longint;

function Frac(x : real) : real;

function FSearch(Path: PathStr;DirList:string) PathStr;

function Int(x real) real;

function KeyPressed Boolean;

function Length(s Integer;

function MaxAvail

function MemAvail

procedure MsDos (

string)

Longint;

Longint;

var Regs : Registers);

function Odd(x : Longint) Boolean;

Returns the end-of-line status of a file.

Returns the exponential of the argument.

Returns the current file position of a file.

Returns the current size of a file.

Returns the fractional part of the argument.

Searches for a file in a list of directories by DirList. The directories in DirList must be separated by semicolons. The PathStr type is defined in the Dos unit as string [79]. Unit Name Dos.

Returns the Integer part of the argument.

Returns True if a key has been pressed on the keyboard, and False otherwise. Unit name Crt.

Returns the dynamic length of a string.

Returns the size of the largest contiguous free block in the heap, corresponding to the size of the largest dynamic variable that can be allocated at that time.

Returns swn of all free blocks in the heap.

Executes a DOS fimction call. Unit name Dos.

Tests if the argument is an odd nwnber.

Pascal reference 319

Ord

SeekEoln

Sin

UpCase

WhereX

WhereY

function Ord(x) Longint;

function SeekEoln [ (var f: text) ]: Boolean;

function Sin(x : real) : real;

function UpCase(ch : Char) Char;

function WhereX Byte;

function WhereY Byte;

Returns the ordinal number of an ordinal-type value.

Returns the end-of-line status of a file.

Returns the sine of the argument.

Converts a character to upper case.

Returns the x-co-ordinate of the current cursor position, relative to the current window. Unit name Crt.

Returns the y-eo-ordinate of the current cursor position, relative to the current window. Unit name Crt.

The following is a quick reference to commonly used procedures.

Append

Assign

BlockRead

Block Write

ChDir

Close

procedure Append(var f : text) ;

procedure Assign(var f; name : string);

procedure BlockRead(var f: file; var buf;count : Word [; var result: Word] )

procedure BlockWrite(var f: file;var buf; count: Word [; var result: Word])

procedure ChDir(s : string);

procedure Close(var f);

320 Mastering Pascal

Opens an existing file for appending.

Assigns the name of an external file to a file variable.

Reads one or more records into a variable, where f is an untyped file variable, buf is any variable, count is an expression of type Word, and result is a variable of type Word.

Writes one or more records from a variable, where f is an untyped file variable, buf is any variable, count is an expression of type Word, and result is a variable of type Word.

Changes the current directory.

Closes an open file.

ClrEol

ClrScr

Dec

Delay

Delete

DelLine

Erase

Exec

Exit

Fill Char

FindFirst

FindNext

procedure ClrEol; Clears all characters from the cursor position to the end of the line without moving the cursor. Unit name Crt.

procedure ClrScr; Clears the active window and places the cursor in the upper left-hand corner. Unit name Crt.

procedure Dec (var x Decrements a variable. [ ; n : Longint]);

procedure Delay (MS : Word) ; Delays a specified number of

milliseconds. Unit name Crt.

procedure Delete (var s : Deletes a substring from a string. string; index : Integer; count : Integer);

procedure DelLine; Deletes the line containing the cursor.

procedure Erase(var f);

procedure Exec(Path, CmdLine: string);

procedure Exit;

procedure FillChar(var x; count :Word; ch: Char);

procedure FindFirst(Path string; Attr : Word; var S : SearchRec);

procedure FindNext(var S SearchRec);

Erases an external file.

Executes a specified program with a specified command line. Unit name Dos.

Exits immediately from the current block. If the current block is the main program, it causes the program to terminate.

Fills a specified number of contiguous bytes with a specified value.

Searches the specified (or current) directory for the first entry matching the specified file name and set of attributes. Unit name Dos.

Returns the next entry that matches the name and attributes specified in an earlier call to FindFirst. Unit name Dos.

Pasca/re;rerence 321

Flush

FreeMem

GetCBreak

GetDate

GetDir

GetFAttr

GetFTime

GetlntVec

GetMem

Get Time

GotoXY

Halt

High Video

Inc

procedure Flush(var f text);

procedure FreeMem(var p pointer; size : Word);

procedure GetCBreak(var Break: Boolean);

procedure GetDate{var Year, Month, Day, DayOfWeek : Word);

procedure GetDir{d : Byte; var s : string);

procedure GetFAttr(var F; var Attr : Word);

procedure GetFTime(var F; var Time : Longint);

Flushes the buffer of a text file open for output.

Disposes a dynamic variable of a given size. Should not be used with Mark or Release.

Returns the state of Ctrl-Break checking in DOS. Unit Name Dos.

Returns the current date set in the operating system. Unit name Do s.

Returns the current directory of a specified drive.

Returns the attributes of a file. Unit name Dos.

Returns the date and time a file was last written. Unit name Dos.

procedure GetintVec (IntNo : Returns the address stored in a Byte; var Vector : pointer);

specified interrupt vector. Unit

procedure GetMem(var p : pointer; size : Word);

procedure GetTime{var Hour, Minute, Second, SeclOO : Word);

procedure GoToXY{X, Y Byte);

procedure Halt [ {exitcode Word ) ) ;

procedure HighVideo;

procedure Inc{var x [ ; n : Longint J );

name Dos.

Creates a new dynamic variable of the specified size and puts the address of the block in a pointer variable.

Returns the current time set in the operating system. Unit name Do s.

Positions the cursor. Unit name Crt.

Stops program execution and returns to the operating system.

Selects high intensity characters. Unit name Crt.

Increments a variable.

322 Mastering Pascal

Insert

lnsLine

Intr

Keep

MkDir

Move

NoSound

Randomize

Read

ReadLn

Rename

Reset

Rewrite

RmDir

Seek

SetCBreak

SetDate

procedure Insert(source : string; var s : string; index: Integer);

procedure InsLine;

procedure Intr(IntNo : Byte; var Regs: Registers);

procedure Keep(ExitCode Word);

procedure MkDir(s : string);

procedure Move(var source, dest; count : Word);

procedure NoSound;

procedure Randomize;

procedure Read(f , vl [, v2, ... ,vn ] ) ;

procedure ReadLn( [ var f text; ] vl [, v2, ... ,vn] ) ;

procedure Rename(var f; newname: string);

procedure Reset(var f file; recsize : Word ) ;

procedure Rewrite(var f file [;recsize: Word J );

procedure RmDir(s: string);

procedure Seek(var f; n : Longint);

procedure SetCBreak(Break: Boolean);

procedure SetDate(Year, Month, Day: Word);

Inserts a substring into a string.

Inserts an empty line at the cursor position. Unit name Crt.

Executes a specified software interrupt. Unit name Do s.

Keep (or Terminate Stay Resident) terminates the program and makes it stay in memory. Unit name Dos.

Creates a subdirectory.

Copies a specified number of contiguous bytes from a source range to a destination range.

Turns off the internal speaker.

Initializes the built-in random generator with a random value.

Reads a file component into a variable.

Executes the Read procedure, then skips to the next line of the file.

Renames an external file.

Opens an existing file.

Creates and opens a new file.

Removes an empty subdirectory.

Moves the current position of a file to a specified component.

Sets the state of Ctrl-Break checking in DOS. Unit Name Do s.

Sets the current date in the operating system. Unit name Dos.

Pascal reference 323

SetFAttr

SetFTime

SetlntVec

SetTime

Str

TextColor

TextMode

Truncate

Val

Window

Write

WriteLn

procedure SetFAttr(var F; Attr : Word);

procedure SetFTime(var F; Time : Longint);

procedure SetintVec(IntNo Byte; Vector : pointer);

procedure SetTime(Hour, Minute, Second, SeclOO Word);

procedure Str(x [ : width [ : decimals ]]; var s : string);

procedure TextColor(Color Byte) ;

procedure TextMode(Mode Integer);

procedure Truncate(var f);

procedure Val(s : string; var v; var code : Integer);

procedure Window(Xl, Yl, X2, Y2 : Byte);

procedure Write(f, vl [, v2, ... ,vn ] ) ;

procedure WriteLn( [ var f : text; ] vl [, v2, ... ,vn l ) ;

324 Mastering Pascal

Sets the attributes of a file. Unit name Dos.

Sets the date and time a file was last written. Unit name Dos.

Sets a specified interrupt vector to a specified address. Unit name Do s.

Sets the current time in the operating system. Unit name Dos.

Converts a numeric value to the same string representation that would be output by Write.

Selects the foreground character colour. Unit name Crt.

Selects a specific text mode. Unit name Crt.

Truncates the file size at the current file position.

Converts the string value to its numeric representation, as if it were read from a text file with Read. s is a string-type variable; it must be a sequence of characters that form a signed whole number. vis an integer-type or real-type variable.

Defines a text window on the screen. Unit name Crt.

Writes a variable into a file component.

Executes the Write procedure, then outputs an end-of-line marker to the file.

B ASCII

ANSI defined a standard alphabet known as ASCII. This has since been adopted by the CCITT as a standard, known as lAS (International Alphabet No. 5). The following tables define this alphabet in binary, as a decimal, as a hexadecimal value and as a character.

Bina Decimal Hex Character Bina Decimal Hex Character 00000000 0 00 NUL 00010000 16 10 OLE 00000001 1 01 SOH 00010001 17 11 DCl 00000010 2 02 STX 00010010 18 12 DC2 00000011 3 03 ETX 00010011 19 13 DC3 00000100 4 04 EOT 00010100 20 14 DC4 00000101 5 05 ENQ 00010101 21 15 NAK 00000110 6 06 ACK 00010110 22 16 SYN 00000111 7 07 BEL 00010111 23 17 ETB 00001000 8 08 BS 00011000 24 18 CAN 00001001 9 09 HT 00011001 25 19 EM 00001010 10 OA LF 00011010 26 lA SUB 00001011 11 OB VT 00011011 27 lB ESC 00001100 12 oc FF 00011100 28 lC FS 00001101 13 OD CR 00011101 29 lD GS 00001110 14 OE so 00011110 30 lE RS 00001111 15 OF SI 00011111 31 lF us

Bina Decimal Hex Character Bina Decimal Hex Character 00100000 32 20 SPACE 00110000 48 30 0 00100001 33 21 00110001 49 31 1 00100010 34 22 00110010 50 32 2 00100011 35 23 # 00110011 51 33 3 00100100 36 24 $ 00110100 52 34 4 00100101 37 25 % 00110101 53 35 5 00100110 38 26 & 00110110 54 36 6 00100111 39 27 I 00110111 55 37 7 00101000 40 28 ( 00111000 56 38 8 00101001 41 29 ) 00111001 57 39 9 00101010 42 2A * 00111010 58 3A 00101011 43 2B + 00111011 59 3B 00101100 44 2C 00111100 60 3C < 00101101 45 20 00111101 61 3D 00101110 46 2E 00111110 62 3E > 00101111 47 2F I 00111111 63 3F ?

325

Bina Decimal Hex Character Bina Decimal Hex Character 01000000 64 40 @ 01010000 80 50 p

01000001 65 41 A 01010001 81 51 Q 01000010 66 42 B 01010010 82 52 R 01000011 67 43 c 01010011 83 53 s 01000100 68 44 D 01010100 84 54 T 01000101 69 45 E 01010101 85 55 u 01000110 70 46 F 01010110 86 56 v 01000111 71 47 G 01010111 87 57 w 01001000 72 48 H 01011000 88 58 X 01001001 73 49 I 01011001 89 59 y 01001010 74 4A J 01011010 90 SA z 01001011 75 48 K 01011011 91 58 [ 01001100 76 4C L 01011100 92 sc \ 01001101 77 40 M 01011101 93 50 l 01001110 78 4E N 01011110 94 SE 01001111 79 4F 0 01011111 95 SF

Bina Decimal Hex Character Bina Decimal Hex Character 01100000 96 60 01110000 112 70 p 01100001 97 61 a 01110001 113 71 q 01100010 98 62 b 01110010 114 72 r 01100011 99 63 c 01110011 115 73 s 01100100 100 64 d 01110100 116 74 t 01100101 101 65 e 01110101 117 75 u 01100110 102 66 f 01110110 118 76 v 01100111 103 67 g 01110111 119 77 w 01101000 104 68 h 01111000 120 78 X

01101001 105 69 i 01111001 121 79 y 01101010 106 6A j 01111010 122 7A z 01101011 107 6B k 01111011 123 78 01101100 108 6C 1 01111100 124 7C 01101101 109 60 m 01111101 125 70 01101110 110 6E n 01111110 126 7E 01101111 111 6F 0 01111111 127 7F DEL

326 Mastering Pascal

The standard ASCII character set is a 7 -bit character and ranges from 0 to 127. This code is rather limited as it does not contain symbols such as Greek letters, lines, and so on. For this purpose the extended ASCII code has been defmed. This fits into character numbers 128 to 255. The following four ta-bles defme a typical extended ASCII character set.

Bina Decimal Hex Character Bina Decimal Hex Character 10000000 128 80 c;: 10010000 144 90 E 10000001 129 81 i.i 10010001 145 91 cE

10000010 130 82 e 10010010 146 92 .IE 10000011 131 83 a 10010011 147 93 0 10000100 132 84 a 10010100 148 94 0 10000101 133 85 a 10010101 149 95 0 10000110 134 86 a. 10010110 150 96 u 10000111 135 87 9 10010111 151 97 u 10001000 136 88 e 10011000 152 98 y 10001001 137 89 e 10011001 153 99 b 10001010 138 SA e 10011010 154 9A 0 10001011 139 8B i 10011011 155 9B ¢

10001100 140 ac i 10011100 156 9C £ 10001101 141 80 i 10011101 157 90 ¥ 10001110 142 BE A 10011110 158 9E g

10001111 143 SF A. 10011111 159 9F f

Bina Decimal Hex Character Bina Decimal Hex Character 10100000 160 AO a 10110000 176 BO I 10100001 161 A1 i 10110001 177 B1 10100010 162 A2 6 10110010 178 B2 10100011 163 A3 u 10110011 179 B3 I 10100100 164 A4 fi 10110100 180 B4 i 10100101 165 AS N 10110101 181 BS ~ 10100110 166 A6 a 10110110 182 B6 ~I 10100111 167 A7 10110111 183 B7 11 10101000 168 AS (. 10111000 184 B8 'l 10101001 169 A9 10111001 185 B9 ~I 10101010 170 AA 10111010 186 BA II 10101011 171 AB 11 10111011 187 BB ] 10101100 172 AC ~ 10111100 188 BC 10101101 173 AD i 10111101 189 BD .JI

10101110 174 AE « 10111110 190 BE d

10101111 175 AF » 10111111 191 BF

ASCII 327

Bina Decimal Hex Character Bina Decimal Hex Character 11000000 192 co 11010000 208 DO 11000001 193 C1 .l 11010001 209 D1 'f 11000010 194 C2

1 11010010 210 D2 l 11000011 195 C3 11010011 211 D3

11000100 196 C4 - 11010100 212 D4 b 11000101 197 C5 t 11010101 213 D5 r 11000110 198 C6 11010110 214 D6 II" 11000111 199 C7 I~ 11010111 215 D7 * 11001000 200 c8 l!. 11011000 216 D8 + 11001001 201 C9 If 11011001 217 D9 J

11001010 202 CA d!. 11011010 218 DA I 11001011 203 CB l 11011011 219 DB

11001100 204 cc 11011100 220 DC r 11001101 205 CD 11011101 221 DD 11001110 206 CE JL 11011110 222 DE I 11001111 207 CF I 11011111 223 DF

Bina Decimal Hex Character Bina Decimal Hex Character 11100000 224 EO ()( 11110000 240 FO E 11100001 225 E1 B 11110001 241 F1 ± 11100010 226 E2 r 11110010 242 F2 ~ 11100011 227 E3 n 11110011 243 F3 :;; 11100100 228 E4 ~ 11110100 244 F4 ( 11100101 229 E5 a 11110101 245 F5 J 11100110 230 E6 J.l 11110110 246 F6 + 11100111 231 E7 T 11110111 247 F7 "" 11101000 232 E8 ~ 11111000 248 F8 0

11101001 233 E9 e 11111001 249 F9 11101010 234 EA Q 11111010 250 FA 11101011 235 EB 0 11111011 251 FB ..) 11101100 236 EC cp 11111100 252 FC 11101101 237 ED ~ 11111101 253 FD 11101110 238 EE E 11111110 254 FE • 11101111 239 EF A 11111111 255 FF D

Pascal character conversion examples:

var ch:char; val:integer;

begin ch:= 'a'; val: =ord ( ch) ; (* convert to an ASCII integer *) writeln ('ASCII value for an "A" character is ',val) ; val:=65; ch:=chr(val); (* convert to an ASCII character *) writeln ('ASCII character is a 65 is ', ch); write ('New-line character is ', #13, ' the bell is ', #7) ;

end.

328 Mastering Pascal

C Bits, Bytes and Operators

I C.l Bits and bytes

A computer operates on binary digits named bits. These can either store a ' 1' or a '0' (ON/ OFF). A group of 4 bits is a nibble and a group of 8 bits a byte. These 8-bits provide 256 different combinations of ON/OFF, from 00000000 to 11111111. A 16-bit field is known as a word and a 32-bit field as a long word. Binary data is stored in memories which are either permanent or non­permanent. This data is arranged as bytes and each byte has a different mem­ory address, as illustrated in Figure C.1.

0 1 1 0 0 0 1

0 0 1 0 1 0 0

1 1 1 0 0 0 0

0 1 1 1 1 0 1

I I

t t

0

0

0

0

Memory address

....__ 0

.---2

..-- 3

Figure C.1 Memory storage (each address holds eight bits)

C.l.l Binary numbers

A computer operates on binary digits which use a base-2 numbering system. To determine the decimal equivalent of a binary number each column is repre­sented by 2 raised to the power ofO, 1, 2, and so on. For example, the decimal equivalents of 1000 0001 and 0101 0011 are:

128 64 0

0

32 0 0

16 0 1

8 0 0

4 0 0

2 0

Decimal 129 83

329

equivalents of 1000 0001 and 0101 0011 are:

.---2

2 2 2

Thus 01001111 gives:

(Ox128) + (lx64) + (Ox32) + (Ox16)+ (1x8) + (1x4) + (1x2) + (1x1) = 95

The number of decimal values that a binary number can represent relates to the number of bits. For example:

• 8 bits gives 0 to 2s_1 (255) different representations; • 16 bits gives 0 to 216_1 (65 535) different representations; • 32 bits gives 0 to 232_ 1 ( 4 294 967 295) different representations.

The most significant bit (msb) is at the left-hand side of the binary number and the least significant bit (lsb) on the right-hand side. To convert from decimal (base-10) to binary the decimal value is divided by 2 recursively and remainder noted. The first remainder gives the least significant digit (LSD) and the last the most significant digit (MSD). For example:

2 54 27 rO <<<LSD 13 r 1 6 r 1 3 rO 1 r 1 0 r 1 <<<MSD

Thus 11 0 11 0 in binary is 54 decimal.

I C.2 Binary arithmetic

The basic binary addition operation is given next.

0+0 =0 1 + 0 = 1 1+1 =10 1+1+1 =11

This is used when adding two binary numbers together. For example:

0010001 0001111 0100000

11111

330 Mastering Pascal

I C.3 Numbers and representations

Numbers are stored in several different ways. These can be:

• Integers or floating point values. • Single precision or double precision numbers. • Signed or unsigned integers.

C.3.1 Negative numbers

Signed integers use a notation called 2s complement to represent negative values. In this representation the binary digits have a '1' in the most signifi­cant bit column if the number is negative, else it is a '0'. To convert a decimal value into 2s complement notation, the magnitude of the negative number is represented in binary form. Next, all the bits are inverted and a '1' is added. For example, to determine the 16-bit 2s complement of the value -65, the following steps are taken:

+65 invert add 1

00000000 01000001 1111111110111110 1111111110111111

Thus, -65 is 11111111 1011111 in 16-bit 2s complement notation. Table C.1 shows that with 16 bits the range of values that can be represented in 2s com­plement is from -32 767 to 32 768 (that is, 65 536 values).

Table C.1 16-bit 2s complement notation

Decimal 2s complement -32 768 10000000 00000000 -32 767 10000000 00000001

-2 1111111111111110 -1 1111111111111111

0 00000000 00000000 1 00000000 00000001 2 00000000 00000010

.. .. 32 766 0111111111111110 32 767 0111111111111111

When subtracting one value from another the value to be taken away is first converted into 2s complement format. This is then added to the other value and the result is in 2s complement. For example, to subtract 42 from 65, first 42 is converted into 2s complement (that is, -42) and added to the binary equivalent of 65. The result gives a carry into the sign bit and a carry-out.

Bits, bytes and operators 331

65 -42

0100 0001 1101 0110

(1) 0001 0111

C.3.2 Hexadecimal and octal numbers

In assembly language binary numbers are represented with a proceeding b, for example 01010111101 Ob and 10111110101 Ob are binary numbers. Bi­nary digits are often commonly represented in hexadecimal (base 16) or octal (base 8) representation. Table C.2 shows the basic conversion between deci­mal, binary, octal and hexadecimal numbers. In this text, hexadecimal num­bers have a proceeding h. For example, 4 3 F1h is a hexadecimal value.

To represent a binary digit as a hexadecimal value the binary digits are split into groups of four bits (starting from the least significant bit). A hexa­decimal equivalent value then replaces each of the binary groups. For exam­ple, to represent 0 111 0 1 0 111 0 0 0 0 0 0 b the bits are split into sections of 4 to give:

Binary 0111 0101 1100 0000 Hex 7 5 c 0

Table C.2 Decimal, binary, octal and hexadecimal conversions

Decimal Binary Octal Hex 0 0000 0 0 1 0001 1 1 2 0010 2 2 3 0011 3 3 4 0100 4 4 5 0101 5 5 6 0110 6 6 7 0111 7 7 8 1000 10 8 9 1001 11 9 10 1010 12 A 11 1011 13 B 12 1100 14 c 13 1101 15 D 14 1110 16 E 15 1111 17 F

Thus, 75C0h represents the binary number 0111010111000000b. To convert from decimal to hexadecimal the decimal value is divided by 16 re­cursively and each remainder noted. The first remainder gives the least sig­nificant digit and the fmal remainder the most significant digit. For example, the following shows the hexadecimal equivalent of the decimal number 11 0 3:

332 Mastering Pascal

6 8 r F <<<LSD (least significant digit) 1611103

4 r4

0 r 4 <<< MSD (most significant digit)

Thus the decimal value 110 3 is equivalent to 0 4 4 Fh. In Pascal, hexadecimal values are preceded by a dollar sign ($), for exam­

ple $C4.

I C.4 Pascal operators

Pascal has a rich set of operators; there are four main types:

• Arithmetic. • Logical. • Bitwise. • Relational.

C.4.1 Arithmetic

Arithmetic operators operate on numerical values. The basic arithmetic op­erations are add(+), subtract(-), multiply(*), divide(/) and modulus divi­sion (mod). Modulus division gives the remainder of an integer division. The following gives the basic syntax of two operands with an arithmetic operator.

operand operator operand

The assignment operator ( : =) is used when a variable 'takes on the value' of an operation. Table C.3 summarizes the arithmetic operators.

Table C.3 Arithmetic operators

Operator Operation Example subtraction or minus 5-4-+1

+ addition 4+2-+6 * multiplication 4*3-+12 I division 4/2-+2 div integer division 5 div 2 -+2 mod modulus 13%3-+1 := assignment X = 1

Bits, bytes and operators 333

C.4.2 Relationship

The relationship operators determine whether the result of a comparison is TRUE or FALSE. These operators are greater than (> ), greater than or equal to(>=), less than(<), less than or equal to(<=), equal to(=) and not equal to ( <>).Table C.41ists the relationship operators.

Table C.4 Relationship operators

Operator Function Example TRUE Condition > greater than (b>a) when b is greater than a

>= greater than or equal (a>=4) when a is greater than or equal to 4

< less than (c<f) when cis less than f

<= less than or equal (x<=4) when x is less than or equal to 4

equal to (x==2) when x is equal to 2

<> not equal to (y!=x) when y is not equal to x

C.4.3 Logical (TRUE or FALSE)

A logical operation is one in which a decision is made as to whether the op­eration performed is TRUE or FALSE. If required, several relationship opera­tions can be grouped together to give the required fimctionality. Table C.5 lists the logical operators.

Table C.S Logical operators

Operator Example TRUE condition and ((x=l) and (y<2)) whenxisequaltolandyisless than2

or ( ( a<>b) or ( a>O) ) when a is not equal to bora is greater than 0

not (not (a>O)) when a is not greater than 0

Logical and operation will only yield a TRUE only if all the operands are TRUE. Table C.6 gives the result of the and operator for the operation Op­erandl and Operand2. The logical OR operation yields a TRUE if any one of the operands is TRUE. Table C.6 gives the logical results of the or operator for the statement Operandl or Operand2.

334 Mastering Pascal

Table C.6 Logical truth table for and and or

Operandl Operand2 and or

FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE

Table C.7 gives the logical result of the NOT operator for the statement not (Operand).

Table C. 7 NOT logical truth table

Operand FALSE TRUE

Result TRUE FALSE

For example, if a has the value 1 and b is also 1, then the following rela­tionship statements would apply:

C.4.4 Bitwise

Statement (a=l) and (b=l) (a>l) and (b=l) (a=lO) or (b=l) not(a=12)

Result TRUE FALSE TRUE TRUE

The bitwise operators are similar to the logical operators but they should not be confused as their operation differs. Bitwise operators operate directly on the individual bits of an operand(s), whereas logical operators determine whether a condition is TRUE or FALSE.

The basic bitwise operations are and, or, xor, shl and shr. Table C.8 gives the results of the AND bitwise operation on two bits Bi tl and Bi t2. Table C.8 also gives the truth table for the bit operation of the or and xor bitwise operators with two bits Bi tl and Bi t2.

Table C.S Bitwise and, or and xor truth table

Bitl Bit2 and or xor 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0

Bits, bytes and operators 335

Table C.9 gives the truth table for the not bitwise operator on a single bit.

Table C.9 Bitwise not truth table

Bit Result

0 1 1 0

The bitwise operators operate on each of the individual bits of the oper­ands. For example, if two decimal integers 58 and 41 (assuming eight-bit un­signed binary values) are operated on using the AND, OR and EX-OR bitwise operators, then the following will apply.

58 41

Result

AND 00111010 00101001 00101000

OR 00111010 00101001 00111011

EX-OR 00111010 00101001 00010011

The results of these bitwise operations are as follows:

58 and 41 58 or 41 58 xor 41

40 59 19

(00101000) (00111011) (00010011)

To perform bit shifts, the shl and shr operators are used. These shift the bits in the operand by a given number defmed by a value given on the right­hand side ofthe operation. The left shift operator (shl) shifts the bits of the operand to the left and zeros fill the result on the right. The right shift operator (shr) shifts the bits of the operand to the right and zeros fill the result if the integer is positive; otherwise it will fill with 1 's. The standard format is:

operand >> no_of_bit_shift_positions operand << no_of_bit shift_positions

For example, if y = 59 (00111011), then y shr 3 will equate to 7 (00000111) andy shl 2 to 236 (11101100).

C.4.5 Precedence

The rules of precedence are:

1. An operand between two operators of different precedence is bound to the

336 Mastering Pascal

operator with higher precedence. 2. An operand between two equal operators is bound to the one on its left. 3. Expressions within parentheses are evaluated before being treated as a

single operand. 4. The priority levels for operators are as follows:

IDGHEST PRIORITY

() primary not unary

* I div mod arithmetic and multiply and shl shr operators + - or xor additive operators = <> < > relational

< > <= >= comparison

LOWEST PRIORITY

For example:

23 + 5 mod 3 div 2 shl 1 => 23 + 2 div 2 shl 1 => 23 + 1 shl 1 => 23 + 2 => 25

Bits, bytes and operators 337

D Delphi Reference

I D.l Standard units

The main Delphi units are:

• Buttons. Contains declarations for SpeedButtons and bitmapped buttons. • Classes. Contains declarations for many of the base object classes. • ClipBrd. Contains declaration for the clipboard object and creates an in­

stance of the clipboard. • Controls. Contains declarations for TControl, TWinControl, TGraphic­

Control and TCustomControl and their associated routines and types. • DB. Contains declarations for the TDatabase, TDataSource, and TField

components and includes their associated routines and types. • DBGrids. The DBGrids unit contains the declarations for the database grid

and its associated routines and types. • DDEMan. Contains components and types for dynamic-data exchange

(DDE). • Dialogs. Contains declarations for the common dialog boxes which are

found on the Dialogs page of the Component palette and routines for dis­playing message boxes.

• ExtCtrls. Contains the declarations for the certain components on the Standard and Additional pages of the Component palette.

• FileCtrl. Contains the declarations for the certain components on the Sys­tem page of the Component palette.

• Forms. Contains declarations for TForm and its associated objects, types, and routines.

• Graphics. Contains Delphi support for Windows GDI unit. • Grids. Contains the declarations for TDrawGrid, and TStringGrid and

their associated types routines. • IniFiles. Contains the declaration for an object which enables you to read

and write your own .INI files. • Mask. Contains declarations character masks and picture fields. • Menus. Contains declarations for TMainMenu and TPopupMenu and their

associated objects, types, and routines.

338

• Mplayer. Contains declarations for the media player component. • Outline. Contains declarations for TOutline. • Printers. Contains declarations for TPrinter and its associated objects. • Report. Contains declarations for TReport and its associated objects. • StdCtrls. Contains declarations for the components that appear on the

Standard page of the Component palette. • System. Contains Delphi run-time library, which implements low-level

run-time support routines for all built-in features. • SysUtils. Contains declarations for exception classes, string routines, date

and time routines and utility routines. • TOCtrl. Contains declarations for the Ole container for object linking and

embedding with other OLE applications. • WinProcs. Defmes function and procedure headers for the Windows API. • WinTypes. Defmes all the types used by Windows API routines.

I D.2 Forms unit

The Forms unit contains declarations for TForm and all its associated ob­jects, types, and routines. The following items are declared in the Forms unit:

Components TForm TScrollBox

Objects TApplication TControlScrollBar TOe signer TScreen TScrollingWinControl

Types TBordericons TBorderStyle TCloseAction TCloseEvent TCloseQueryEvent TCursorRec TExceptionEvent TFormBorderStyle TFormClass TFormState TFormStyle TidleEvent TMessageEvent TModalResult

Delphi reference 339

TPosition TPrintScale TScrollBarinc TScrollBarKind TShowAction TTileMode TWindowHook TWindowState TWndMethod

Variables Application HintWindow Screen

Constants Ctl3DBtnWndProc Ctl3DCtlColorEx Ctl3DDlgFramePaint

Routines AllocateHWnd DeallocateHWnd DisableTaskWindow EnableTaskWindow FreeObjectinstance GetarentForm IsAccel KeyDataToShiftState KeysToShiftState MakeObjectinstance ValidParentForm

I D.3 WinProcs Unit

The WinProcs unit defines function and procedure headers for the Windows API. These routines provide access to the standard Win32 libraries. They in­clude:

bread File read hwrite File write lclose Close a file lcreat File creation llseek Moves file pointer

_lopen File open lread File read -lwrite File write

AbortDoc Print job termination

340 Mastering Pascal

AddFontResource AdjustWindowRect AllocDiskSpace AllocDStoCSAlias AllocFileHandles AllocGDIMem AllocMem AllocResource AllocUserMem AnsiLower AnsiLowerBuff AnsiNext AnsiPrev AnsiToOem AnsiUpper AnsiUpperBuff Any Popup AppendMenu Arc Arrangelconic Windows BeginPaint BitBlt CallWindowProc Catch ChangeClipboardChain CheckDlgButton CheckMenultem CheckRadioButton ChooseColor ChooseFont Chord ClearConiDUBreak ClientToScreen ClipCursor CloseClipboard CloseComm CloseDriver CloseMetaFile Close Window CombineRgn CopyCursor Copy leon CopyLZFile Copy MetaFile CopyRect CountClipboardF ormats CreateBitmap

Adds a font to the font table Determines the required size of a window rectangle Creates a file with some disk space Translates a data segment to a code segment Allocates file handles Allocates all available memory in the GDI heap. Allocates all available memory. Allocates memory for a resource Allocates all available memory in the User heap. Converts a string to lower case Converts a string buffer to lower case Moves to the next character in a string Move to the previous character in a string Translates a Windows string to an OEM string Converts a string to upper case Converts a string buffer to upper case Indicates if pop-up or overlapped window exists Appends a new item to a menu Draws an arc Arranges minimized child windows Prepares a window for painting Copies a bitmap between device contexts Passes a message to a window procedure Captures the current execution environment Removes a window from the clipboard-viewer chain Changes a check mark by a dialog button Changes a check mark by a menu item Places a check mark by a radio button Creates a colour-selection dialog box Creates a font-selection dialog box Draws a chord Restores character transmission Converts client point to screen coordinates Confines the cursor to a specified rectangle Closes the clipboard Closes a communications device Closes an installable driver Closes metafile de and gets handle Minimizes a window Creates a region by combining two regions Copies a cursor Copies an icon Copies a file and decompresss it if compressed Copies a metafile Copies the dimensions of a rectangle Returns the number of clipboard formats Creates device-dependent memory bitmap

Delphi reference 341

CreateCursor Creates a cursor with specified dimensions CreateDC Creates a device context CreateDialog Creates a modeless dialog box CreateDIBitmap Creates bitmap handle from DIB spec CreateDffiPatternBrush Creates a pattern brush from a DIB CreateEllipticRgn Creates an elliptical region CreateEllipticRgnlndirect Creates an elliptical region CreateFont Creates a logical font CreateHatchBrush Creates a hatched brush Create leon Create Menu CreateMetaFile CreatePalette CreatePatternBrush CreatePen CreatePolygonRgn CreatePolyPolygonRgn CreatePopupMenu CreateRectRgn CreateRoundRectRgn CreateSolidBrush Create Window DdeAbandonTransaction DdeAccessData DdeAddData DdeClientTransaction DdeCmpStringHandles DdeConnect DdeConnectList DdeCreateDataHandle DdeCreateStringHandle DdeDisconnect DdeDisconnectList DdeEnableCallback DdeFreeDataHandle DdeFreeStringHandle DdeGetData DdeGetLastError Ddelnitialize DdeKeepStringHandle DdeNameService DdePostAdvise DdeQueryConvlnfo DdeQueryNextServer DdeQueryString DdeReconnect DdeSetU serHandle

Creates an icon with the specified dimensions Creates a menu Creates a metafile device context Creates a logical colour palette Creates a pattern brush from a bitmap Creates a pen Creates a polygonal region Creates a region consisting of polygons Creates a pop-up window Creates a rectangular region Creates a rectangular region with round comers Creates a solid brush with a specified colour Creates a window Abandons an asynchronous transaction Accesses a DDE global memory object Adds data to a DDE global memory object Begins a DDE data transaction Compares two DDE string handles Establishes a conversation with a server Establishes multiple DDE conversations Creates a DDE data handle Creates a DDE string handle Terminates a DDE conversation Destroys a DDE conversation list Enables or disables one or more DDE conversations Frees a global memory object Frees a DDE string handle Copies data from a global memory object to a buffer Returns an error code set by a DDEML function Registers an application with the DDEML Increments the usage count for a string handle Registers or unregisters a service name Prompts a server to send advise data to a client Gets information about a DDE conversation Obtains the next handle in a conversation list Copies string-handle text to a buffer Reestablishes a conversation with a server Associates a user-defmed handle with a transaction

342 Mastering Pascal

DdeUnaccessData DdeUninitialize DefDriverProc DeferWindowPos DetFrameProc DefHookProc DefMDIChildProc DefScreenSaverProc DetWindowProc DeleteDC DeleteMenu DeleteMetaFile DeleteObject DestroyCaret DestroyCursor Destroy Icon Destroy Menu Destroy Window DeviceCapabilities DeviceMode DialogBox DialogBoxlndirect DialogBoxlndirectParam DialogBoxParam DirectedYield DispatchMessage DlgChangePassword DlgDirList DlgGetPassword DlginvalidPassword DOS3Call DragAcceptFiles DragFinish DragQueryFile DragQueryPoint DrawF ocusRect Drawicon DrawMenuBar

Frees a DDE global memory object Frees an application's DDEML resources Calls the default installable-driver procedure Updates a multiple window position structure Default MDI frame window message processing Calls the next function in a hook-function chain Default MDI child window message processing Calls default screen-saver window procedure Calls the default window procedure Deletes a device context Deletes an item from a menu Invalidates a metafile handle Deletes an object from memory Destroys the current caret Destroys a cursor Destroys an icon Destroys a menu Destroys a window Gets the capabilities of a device Displays dialog box for printing modes Creates a modal dialog box Creates modal dialog box from template in memory Creates modal dialog box from template in memory Creates a modal dialog box Forces execution to continue at a specified task Dispatches a message to a window Changes password for screen saver Fills a directory list box Gets password for screen saver Warns of invalid screen saver password Issues a DOS Int 2lh function request Registers whether a windows accepts dropped files Releases memory allocated for dropping files Gets filename of dropped file Gets mouse position at file drop Draws a rectangle in the focus style Draws an icon in the specified device context Redraws the menu bar

DrawText Draws formatted text in a rectangle Ellipse Draws an ellipse EmptyClipboard Empties the clipboard and frees data handles EnableCommNotification Enables/disables WM _ COMMNOTIFY posting to window EnableHardwarelnput Controls mouse and keyboard input queuing EnableMenultem Enabls, disables, or grays a menu item EnableScrollBar Enables or disables scroll-bar arrows Enable Window EndDialog

Sets the window-enable state Hides a modal dialog box

Delphi reference 343

EndDoc EndPage EndPaint EqualRect EqualRgn Escape EscapeCommFunction ExcludeClipRect ExcludeUpdateRgn Exit Windows ExitWindowsExec ExtDeviceMode ExtFloodFill Extract! con ExtTextOut FatalAppExit FatalExit FillRect FillRgn FindExecutable FindResource FindText FindWindow Flash Window FloodFill FlushComm FrameRect FrameRgn FreeAllGDIMem FreeAllMem FreeAllUserMem Free Resource FreeSelector GetActive Window GetAspectRatioFilter GetAspectRatioFilterEx GetAsyncKeyState GetBitmapBits GetBitmapDimension GetBitmapDimensionEx GetBkColor GetBkMode GetBoundsRect GetBrushOrg GetBrushOrgEx GetCapture GetCaretBlinkTime

Ends a print job Ends a page Marks end of painting in the specified window Determines whether two rectangles are equal Compares two regions for equality Allows access to device facilities Passes an extended function to a device Changes clipping region, excluding rectangle Excludes an updated region from clipping region Restarts or terminates Windows Terminates Windows, runs MS-DOS app Displays dialog box for printing modes Fills area with current brush Gets handle of icon from executable file Writes a character string in rectangular region Terminates an application Displays debug info., causes breakpoint exception Fills a rectangle with the specified brush Fills a region with a brush Gets name and handle of program for a file Locates a resource in a resource file Creates a find-text dialog box Returns window handle for class and window name Flashes a window once Fills area with current brush Flushes a transmit or receive queue Draws a window border with a specified brush Draws a border around a region Frees memory allocated by AllocGDIMem. Frees memory allocated by AllocMem. Frees memory allocated by AllocUserMem. Unloads a resource instance Frees an allocated selector Gets the handle of the active window Gets setting of aspect-ratio filter Gets current aspect-ratio filter Determines key state Copies bitmap bits to a buffer Gets width and height of bitmap Gets width and height of bitmap Gets the current background colour Gets the background mode Returns current accumulated bounding rectangle Gets the origin of the current brush Gets the origin of the current brush Returns the handle for the mouse-capture window Returns the caret blink rate

344 Mastering Pascal

GetCaretPos GetCharABCWidths GetCharWidth

Returns the current caret position Gets widths ofTrueType characters Gets character widths

GetClasslnfo Returns window class information GetClassLong Returns window-class data GetClassName Returns window class name GetClass Word Returns window class memory word GetClientRect Returns window client area coordinates GetClipboardData Returns a handle to clipboard data GetClipboardFormatNameReturns registered clipboard format name GetClipboardOwner Returns clipboard owner window handle GetClipboardViewer Returns first clipboard viewer window handle GetClipBox Gets rectangle for clipping region GetClipCursor Returns cursor-confining rectangle coordinates GetCodeHandle Determines the location of a function GetCodelnfo GetCommError GetCommEventMask GetCommState GetCurrentPosition GetCurrentPositionEx GetCurrentTask GetCurrentTime GetCursor GetCursorPos GetDC GetDCEx GetDCOrg GetDesktop Window GetDeviceCaps GetDialogBaselJnits GetDIBits GetDlgCtrliD GetDlgltem GetDlgltemlnt GetDlgltemText GetDOSEnvironment GetDoubleClickTime

Gets code-segment information Returns communications-device status Gets the device event mask Reads communications device status Gets current position Gets position in logical units Returns current task handle Returns elapsed time since Windows started Returns current cursor handle Returns current cursor position Returns window device-context handle Gets the handle of a device context Gets translation origin for device context Returns desktop window handle Gets device capabilities Returns dialog base units Copies DIB bits into a buffer Returns child window ID Returns handle of a dialog control Translates dialog text into an integer Gets dialog control text Returns a far pointer to the current environment Returns mouse double click time

GetDriverlnfo Gets installable-driver data GetDriverModuleHandle Gets an installable-driver instance handle GetDriveType GetExpandedName GetFileResource GetFileResourceSize GetFileTitle GetFile V ersionlnfo GetFile VersionlnfoSize

Determines drive type Gets original filename for a compressed file Copies a resource into a buffer Returns the size of a resource Gets a filename Returns version information about a file Returns the size of a file's version information

Delphi reference 345

GetFocus Returns current focus window handle GetFontData Gets font metric data GetFreeFileHandles Returns the number of free file handles GetFreeSpace Returns number of free bytes in the global heap GetFreeSystemResources Returns percentage of free system resource space GetlnputState Returns mouse, keyboard and timer queue status GetlnstanceData Copy previous instance data into current instance GetKBCodePage Returns the current code page GetKerningPairs Gets kerning pairs for current font GetKeyboardState Returns virtual-keyboard keys status GetKeyboardType Gets keyboard information GetKeyNameText Gets string representing the name of a key GetKeyState Returns specified virtual key state GetLastActivePopup Determines most recently active pop-up window GetMapMode Gets mapping mode GetMenu Returns menu handle for the specified window GetMenultemCount Returns the number of items in a menu GetMenultemiD GetMenuState GetMenuString GetMessage GetMessageExtralnfo GetMessagePos GetMessageTime GetMetaFile GetMetaFileBits GetModuleFileName GetModuleHandle

Returns a menu-item identifier Returns status flags for the specified menu item Copies a menu-time label into a buffer Gets a message from the message queue Gets information about a hardware message Returns cursor position for last message Returns the time for the last message Creates handle to a metafile Creates memory block from metafile Returns the file name for a module handle Returns a module handle for a named module

GetModuleUsage Returns the reference count for a module GetNearestColor Gets closest available colour GetNextDlgGroupltem Returns handle of previous or next group control GetNextDriver Enumerates installable-driver instances GetNextWindow Returns next or previous window-manager window GetNumTasks Returns the current number of tasks GetObject Gets information about an object GetOpenClipboardWindow

Returns handle to window that opened clipboard GetOpenFileName Creates an open-filename dialog box GetOutlineTextMetrics Gets metrics for TrueType fonts GetPaletteEntries GetParent GetPixel GetPolyFillMode GetProfilelnt GetProfileString GetProp GetQueueStatus

Gets range of palette entries Returns parent window handle Gets RGB colour of specified pixel Gets the current polygon-filling mode Gets an integer value from WIN.INI Gets a string from WIN.INI Returns data handle from a window property list Determines queued message type

346 Mastering Pascal

GetRasterizerCaps GetRgnBox GetSaveFileName GetScrollPos GetScrollRange GetSelectorBase GetSelectorLimit GetStockObject GetStretchBltMode GetSubMenu GetSysColor GetSystemDir GetSystemDirectory GetSystemMenu GetSystemMetrics GetSystemPaletteEntries GetTempDrive GetTempFileName GetTextAlign GetTextCharacterExtra GetTextColor GetTextExtent GetTextFace GetTextMetrics GetTickCount GetTimerResolution GetTop Window GetUpdateRect GetUpdateRgn Get Version GetViewportExt GetViewportOrg GetWinDebuglnfo Get Window GetWindowDC GetWindowExt GetWindowExtEx GetWindowLong GetWindowOrg GetWindowPlacement GetWindowRect GetWindowsDir GetWindowsDirectory Global32Alloc GlobalAlloc Global Compact GlobalDeleteAtom

Gets status of True Type on system Gets bounding rectangle for region Creates a save-filename dialog box Returns current scroll-bar thumb position Returns minimum and maximum scroll-bar positions Gets the base address of a selector Retrieves the limit of a selector Gets handle of a stock pen, brush, or font Gets the current bitmap-stretching mode Returns pop-up menu handle Returns display-element colour Returns the Windows system subdirectory Returns the Windows system directory Provides access to the System menu Gets the system metrics Gets entries from system palette Returns a disk drive letter for temporary files Creates a temporary filename Gets text-alignment flags Gets intercharacter spacing Gets the current text colour Determines dimensions of a string Gets typeface name of the current font Gets the metrics for the current font Returns amount of time Windows has been running Gets the timer resolution Returns handle for top child of given window Returns window update region dimensions Returns window update region Returns the current Dos and Windows versions Gets viewport extent Gets viewport origin Queries current system-debugging information Returns specified window handle Returns window device context Gets window extents Gets window extents Returns long value from extra window memory Gets window origin Returns window show state and minimax position Gets a window's coordinates Returns the Windows directory Returns the Windows directory Allocates a USE32 memory object Allocates memory from the global heap Generates free global memory by compacting Decrements a global atom's reference count

Delphi reference 34 7

GlobalDosAlloc GlobalDosFree GlobalReAlloc GlobalSize GrayString HiliteMenultem Hmemcpy InflateRect lnsertMenu InterruptRegister InterruptUnRegister InvertRect InvertRgn IsCharAlpha lsCharAiphaNumeric IsCharLower lsCharUpper Is Child lslconic IsMenu IsRectEmpty Is Task Is Window Is WindowEnabled Is WindowVisible lsZoomed Kill Timer Line To LoadAccelerators LoadBitmap Load Cursor Loadlcon LoadLibrary LoadMenu LoadModule LoadResource Load String LocalAlloc LocalFree LocalHandle LogError LogParamError LPtoDP lstrcat lstrcmp lstrcmpi lstrcpy

Allocates memory available to DOS in real mode Frees global memory allocated by GlobalDosAlloc Changes size/attributes of global memory object Returns the size of a global memory object Draws gray text at the specified location Changes highlight of top-level menu item Copies bytes Changes rectangle dimensions Inserts a new item in a menu Installs function to handle system interrupts Removes function that processed system interrupts Inverts a rectangular region Inverts the colours in a region Determines if a character is alphabetical Determines is a character is alphanumeric Determines if a character is lower case Determines if a character is upper case Determines if a window is a child Determines if a window is minimized Determines if a menu handle is valid Determines whether rectangle is empty Determines whether a task handle is valid Determines if a window handle is valid Determines if a window accepts user input Determines visibility state of a window Determines if a window is maximized Removes a timer Draws a line from the current position Loads an accelerator table Loads a bitmap resource Loads a cursor resource Loads an icon resource Returns a handle to a library module Loads a menu resource Loads and executes a program Returns a handle to a resource Loads a string resource Allocate memory from the local heap Frees a local memory object Returns the handle of a local memory object Identifies an error message Identifies a parameter validation error Converts logical points to device points Appends one string to another Compares two character strings Compares two character strings Copies a string to a buffer

348 Mastering Pascal

lstrlen LZClose LZCopy LZDone LZinit LZOpenFile LZRead LZSeek LZStart MemManlnfo Memory Read Memory Write MessageBeep MessageBox Modify Menu ModuleFindHandle ModuleFindName ModuleFirst ModuleNext Move To MoveToEx Move Window MulDiv NetBIOSCall OemKeyScan OemToAnsi OffsetClipRgn OffsetRect OffsetRgn OffsetViewportOrg OffsetViewportOrgEx OffsetWindowOrg OffsetWindowOrgEx OleActivate OleBlockServer OleClose OleCopyFromLink OleCopyToClipboard OleCreate OleCreateFromClip OleCreateFromFile OleCreatelnvisible OleDelete OleDraw OleEnumF ormats OleEnumObjects OleEqual

Returns the number of characters in a string Closes a file Copies a file and expands it if compressed Frees buffers allocated by LZStart Initializes data structures needed for decompression Opens a file (both compressed and uncompressed) Reads a specified number of bytes from a compressed file Repositions pointer in file Allocates buffers for CopyLZFile fimction Gets information about the memory manager Reads memory from an arbitrary global heap object Writes memory to an arbitrary global heap object Generates a beep Creates a message-box window Changes an existing menu item Gets information about a module Gets information about a module Gets information about first module Gets information about next module Moves the current position Moves the current position Changes the position and dimensions of a window Multiplies two values and divides the result Issues a NETBIOS Interrupt 5Ch Maps OEM ASCII to scan codes Translates an OEM string to a Windows string Moves a clipping region Moves a rectangle by an offset Moves a region by a specified offset Moves viewport origin Moves viewport origin Moves window origin Moves window origin Activates an object Queues incoming requests for the server Closes specified object Makes an embedded copy of a linked object Puts the specified object on the clipboard Creates an object of a specified class Creates an object from the clipboard Creates an object from a file Creates an object without displaying it Deletes an object Draws an object into a device context Enumerates data formats for an object Enumerates objects in a document Compares two objects for equality

Delphi reference 349

OleExecute OleGetData Ole Reconnect OleRegisterClientDoc OleRegisterServer OleRegisterServerDoc OleRelease OleRename OleRenameClientDoc OleRenameServerDoc OleRequestData OleRevertClientDoc OleRevertServerDoc OleRevokeClientDoc OleRevokeObject OleRevokeServer OleRevokeServerDoc OleSavedClientDoc OleSavedServerDoc OleSaveToStream OleSetBounds OleSetColorScheme OleSetData OleSetHostNames OleSetTargetDevice OleUnblockServer OleUnlockServer OleUpdate OpenClipboard OpenComm OpenDriver OpenFile Open! con OutputDebugString PaintRgn PatBlt PeekMessage Pie Play MetaFile PlayMetaFileRecord Polygon Polyline PolyPolygon PostAppMessage PostMessage PostQuitMessage PrintDlg

Sends DDE execute commands to a server Gets data for an object in a specified format Reconnects to an open linked object Registers a document with the library Registers the specified server Registers document with server library Releases an object from memory Informs library an object is renamed Informs library a document is renamed Informs library a document is renamed Gets data from a server in a specified format Informs library a doc reverted to saved state Informs library a doc is reset to saved state Informs library a document is not open Revokes access to an object Revokes the specified server Revokes the specified document Informs library a doc has been saved Informs library a doc has been saved Saves an object to the stream Sets bounding rectangle for object Specifies client's recommended object colours Sends data in specified format to server Sets client name and object name for server Sets target device for an object Processes requests from queue Releases server locked with OleLockServer Updates an object Opens the clipboard Opens a communications device Opens an installable driver Creates, opens, reopens or deletes a file Activates a minimized window Sends a character string to the debugger Fills region with brush in device context Creates a bitmap pattern Checks message queue Draws a pie-shaped wedge Plays a metafile Plays a metafile record Draws a polygon Draws line segments to connect specified points Draws a series of polygons Posts a message to an application Places a message in a window's message queue Tells Windows that an application is terminating Creates a print-text dialog box

350 Mastering Pascal

PtlnRect Determines if a point is in a rectangle PtlnRegion Queries whether a point is in a region PtVisible Queries whether point is within clipping region Query Abort Queries whether to terminate a print job QuerySendMessage Determines if a message originated within a task ReadComm Reads from a communications device RealizePalette Maps entries from logical to system palette Rectangle Draws a rectangle RectlnRegion Queries whether rectangle overlaps region RectVisible Queries whether rectangle is in clip region RedrawWindow Updates a client rectangle or region RegisterClass Registers a window class RegisterClipboardFormat Registers a new clipboard format RegisterDialogClasses Registers dialog classes for screen-savers RegisterWindowMessage Defmes a new unique window message RegOpenKey Opens a key RegQueryValue Gets text string for specified key RegSetValue Associates a text string with a specified key ReleaseCapture Releases mouse capture ReleaseDC Frees a device context RemoveF ontResource RemoveMenu RemoveProp Replace Text Reply Message ResetDC ResizePalette RestoreDC RoundRect SaveDC Scale ViewportExt Scale ViewportExtEx Scale WindowExt Scale WindowExtEx ScreenSaverProc ScreenToClient ScrollDC Scroll Window ScrollWindowEx SelectClipRgn SelectObject SelectPalette SendDlgltemMessage SendDriverMessage SendMessage SetAbortProc SetActive Window

Removes font resource Deletes a menu item and pop-up menu Removes a property-list entry Creates a replace-text dialog box Replies to a SendMessage Updates a device context Changes the size of a logical palette Restores device context Draws a rectangle with rounded comers Saves current state of device context Scales viewport extents Scales viewport extents Scales window extents Scales window extents Processes input to a screen-saver window Converts screen point to client coordinates Scrolls a rectangle horizontally and vertically Scrolls a window's client area Scrolls a window's client area Selects clipping region for device context Selects object into a device context Selects a palette into a device context Sends a message to a dialog box control Sends a message to an installable driver Sends a message to a window Sets the abort function for a print job Makes a top-level window active

Delphi reference 351

SetBitmapBits SetBitmapDimension SetBitmapDimensionEx SetBkColor SetBkMode SetBoundsRect SetBrushOrg SetCapture SetClassLong SetClass Word SetClipboardData SetClipboardViewer SetCommBreak SetCommEventMask SetCommState SetCursor SetCursorPos SetDIBits SetDIBitsToDevice SetDlgltemlnt SetDlgltemText SetDoubleClickTime SetErrorMode SetFocus SetHandleCount SetKeyboardState SetMapMode SetMapperFlags SetMenu SetMenultemBitmaps SetMessageQueue SetMetaFileBits SetMetaFileBitsBetter SetPaletteEntries SetParent SetPixel SetPolyFillMode SetProp SetRect SetRectEmpty SetRectRgn SetResourceHandler SetScrollPos SetScrollRange SetSelectorBase SetSelectorLimit SetStretchBltMode

Sets bitmap bits from array of bytes Sets width and height of bitmap Sets width and height of bitmap Sets the current background colour Sets the background mode Controls bounding-rectangle accumulation Sets the origin of the current brush Sets the mouse capture to a window Sets a long value in extra class memory Sets a word value in extra class memory Sets the data in the clipboard Adds a window to the clipboard-viewer chain Suspends character transmission Enables events in a device event mask Sets communications-device state Changes the mouse cursor Sets mouse-cursor position in screen coordinates Sets the bits of a bitmap Sets DIB bits to device Converts an integer to a dialog text string Sets dialog title or item text Sets the mouse double-click time Controls Interrupt 24h Error Handling Sets the input focus to a window Changes the number of available file handles Sets the keyboard state table Sets mapping mode Sets font-mapper flag Sets the menu for a window Associates bitmaps with a menu item Creates a new message queue Creates memory block from metafile Creates memory block from metafile Sets colours and flags for a colour palette Changes a child's parent window Sets pixel to specified colour Sets the polygon-filling mode Adds or changes a property-list entry Sets a rectangle's dimensions Creates an empty rectangle Changes a region into specified rectangle Installs a load-resource callback fimction Sets scroll-bar thumb position Sets minimum and maximum scroll-bar positions Sets the base and limit of a selector Sets the limit of a selector Sets the bitmap-stretching mode

352 Mastering Pascal

SetSwapAreaSize SetSysColors SetSysModalWindow SetSystemPaletteU se SetTextAlign SetTextColor SetTextJustification SetTimer SetViewportExt SetViewportOrg SetWinDebuglnfo SetWindowExt SetWindowOrg SetWindowPlacement SetWindowPos SetWindowsHook SetWindowText SetWindowWord ShellExecute ShowCursor ShowScrollBar Show Window SizeotResource SpoolFile StartDoc StartPage StretchBlt StretchDIBits SubtractRect SwapMouseButton SwitchStackBack SwitchStackTo SystemHeaplnfo SystemParameterslnfo TaskFindHandle TaskFirst TaskGetCSIP TaskNext TaskSetCSIP TaskSwitch TerminateApp TextOut Throw TimerCount ToAscii TrackPopupMenu TranslateAccelerator

Sets the amount of memory used for code segments Sets one or more system colours Makes a window the system-modal window Use of system palette static colours Sets text-alignment flags Sets the foreground colour of text Sets alignment for text output Installs a system timer Sets viewport extents Sets viewport origin Sets current system-debugging information Sets window extents Sets the window origin Sets window show state and min/max position Sets a windows size, position, and order Installs a hook function Sets text in a caption title or control window Sets a word value in extra window memory Opens or prints specified file Shows or hides the mouse cursor Shows or hides a scroll bar Sets window visibility state Returns the size of a resource Puts a file in the spooler queue Starts a print job Prepares printer driver to receive data Copies a bitmap, transforming if required Moves DIB from source to destination rectangle Creates rect from difference of two rects Reverses the meaning of the mouse buttons Restores the current-task stack Changes the location of the stack Gets information about the USER heap Queries or sets system wide parameters Gets information about a task Gets information about first task in task queue Returns the next CS:IP value of a task. Gets information about next task in the task queue Sets the CS:IP of a sleeping task. Switches to a specific address within a new task Terminates an application Writes a character string at specified location Restores the execution environment Gets execution times Translates virtual-key code to Windows character Displays and tracks a pop-up menu Processes menu command keyboard accelerators

Delphi reference 353

TranslateMDISysAccel TranslateMessage TransmitCommChar UnAllocDiskSpace UnAllocFileHandles UngetCommChar UnhookWindowsHook UnionRect UnrealizeObject UnregisterClass UpdateColors Update Window V alidateCodeSegments ValidateFreeSpaces ValidateRect ValidateRgn VerFindFile VerlnstallFile VerLanguageName VerQueryValue VkKeyScan WaitMessage WindowFromPoint WinExec WinHelp WNetAddConnection

Processes MDI keyboard accelerators Translates virtual-key messages Places a character in the transmit queue Deletes the file created by AllocDiskSpace. Frees file handles allocated by AllocFileHandles. Puts a character back in the receive queue Removes a filter function Creates the union of two rectangles Resets brush origins and realizes palettes Removes a window class Updates colours in client area Updates a window's client area Test for memory overwrites Checks free memory for valid contents Removes a rectangle from the update region Removes a region from the update region Determines where to install a file Installs a file Converts a binary language identifier into a string Returns version information about a block Translates Windows character to virtual-key code Suspends an application and yields control Returns window containing a point Runs a program Invokes Windows Help Adds network connections

WNetCancelConnection Removes network connections WNetGetConnection Lists network connections WriteComm Writes to a communications device WriteProfileString Writes a string to WIN.INI wvsprintf Formats a string Yield Stops the current task

I D.4 System unit

The System unit contains Delphi run-time library, which implements low­level run-time support routines for all built-in features. These include:

Abs Addr Append ArcTan Assign Assigned BlockRead

Returns the absolute value of the argument Returns the address of a specified object Opens an existing file for appending Returns the arctangent of the argument Assigns the name of an external file to a file variable Tests to determine if a pointer or procedural variable is nil Reads one or more records into a variable

354 Mastering Pascal

Block Write Break ChDir Chr Close Concat Continue Copy Cos CSeg Dec Delete Dispose DSeg Eof Eoln Erase Exit Exclude Exp FilePos FileSize Fill Char Flush Frac Free FreeMem GetDir GetMem Halt Hi High Inc Include Insert Int IOResult Length Ln Lo Low MaxAvail MernA vail MkDir Move New Odd

Writes one or more records from a variable Terminates a for, while, or repeat statement Changes the current directory Returns a character with a specified ordinal number Closes an open file Concatenates a sequence of strings Continues a for, while, or repeat statement Returns a substring of a string Returns the cosine of the argument Returns the current value of the CS register Decrements a variable Deletes a substring from a string Disposes of a dynamic variable Returns the current value of the DS register Returns the end-of-file status Returns the end-of-line status of a text file Erases an external file Exits immediately from the current block Excludes an element from a set Returns the exponential of the argument Returns the current file position of a file Returns the current size of a file Fills contiguous bytes with a specified value Flushes the buffer of a text file open for output Returns the fractional part of the argument Destroys an object instance Disposes of a dynamic variable of a given size Returns the current directory of specified drive Creates a dynamic variable of the specified size Stops program execution Returns the high-order byte of the argument Returns the highest value in the range of the argument Increments a variable Includes an element from a set Inserts a substring into a string Returns the integer part of the argument Returns the status of the last 1/0 operation performed Returns the dynamic length of a string Returns the natural logarithm of the argument Returns the low-order Byte of the argument Returns the lowest value in the range of the argument Returns the size of the largest free block in the heap Returns the amount of all free memory in the heap Creates a subdirectory Copies bytes from source to destination Creates a new dynamic variable Tests if the argument is an odd number

Delphi reference 355

Ofs Ord ParamCount ParamStr Pi Pos Pred Ptr Random Randomize Read Readln Rename Reset Rewrite RmDir Round RunError ScroliTo Seek SeekEof SeekEoln Seg SetTextBuf Sin SizeOf SPtr Sqr Sqrt SSeg Str Succ Swap Trunc Truncate TypeOf UpCase Val Write Write In

I D.S Dialogs unit

Returns the offset of a specified object Returns the ordinal number of an ordinal-type value Returns the number of parameters passed Returns a specified command-line parameter Returns the value of pi Searches for a substring in a string Returns the predecessor of the argument Converts a segment base and an offset address to a pointer Returns a random number Initializes the built-in random number generator Reads a file component into a variable As Read procedure, then skips to the next line of the file Renames an external file Opens an existing file Creates and opens a new file Removes an empty subdirectory Rounds a real-type value to an integer-type value Stops program execution Scrolls the CRT window to show virtual screen location Moves the current position of a file to a specified component Returns the end-of-file status of a file Returns the end-of-line status of a file Returns the segment of a specified object Assigns an 1/0 buffer to a text file Returns the sine of the argument Returns the number of bytes occupied by the argument Returns the current value of the SP register Returns the square of the argument Returns the square root of the argument Returns the current value of the SS register Converts a numeric value to a string Returns the successor of the argument Swaps the high- and low-order bytes of the argument Truncates a real-type value to an integer-type value Truncates the file at the current file position Returns a pointer to an object type's virtual method table Converts a character to uppercase Converts a string value to its numeric representation Writes a variable into a file component As Write procedure, but outputs an end-of-line marker

The Dialogs unit contains common dialog boxes which are found on the Dialogs page of the Component palette and routines for displaying message

356 Mastering Pascal

boxes. The routines include:

lnputBox InputQuery MessageDlg ShowMessagePos ShowMessage

Displays an input dialog box for string entry Displays an input dialog box for string entry Displays a message dialog box Displays a message box with an OK button Displays a message box with an OK button

Delphi reference 357

I

E Miscellaneous

E.l Structure charts

A structure chart is one method used in the design of structured software. Its approach is similar to schematic diagrams used in electronic design where graphical objects represent electronic devices. The structure chart represents each of the functions (or modules) by rectangular boxes, and the relationship between them is represented by connecting arrows. Data flow is also repre­sented by connecting arrows with a circle at their end. If data goes into a module the arrow points into the module, else if it is being returned then the arrow points away from it. Repetition is denoted by a curved arrow and a de­cision by a diamond. The standard notation for structure charts is given in Figure E.l.

Figure E.2 shows how the flow of data is represented. The main module represents the controlling module (that is, the main program). The diagram shows that main initially calls module modl and passes the parameter vall to it. This module then returns val2 back to main. This value is then passed into mod2 which in turn passes back val3 to main. Figure E.3 shows an example of a decision and iteration. The parameter which controls the deci­sion or iteration may also be shown on the chart.

Referenced module

Dataflow

• Control flag

<> Decision

Iteration

Figure E.1 Structure chart notation

358 Mastering Pascal

Referenced

Standard notation Other possible notation

Figure E.2 Data flow representation

Making a decision Iteration

Figure E.3 Decisions and iteration

I E.2 Programs with errors

The following program have either one or two compiler errors. Locate these errors and correct the programs.

0 Program E.l program test(input,output)

(* Three compiler errors *)

var valuel,value2,average;

begin

end.

writeln('Enter value 1 >>'); readln(valuel); writeln('Enter value 2 >>'); readln(value2);

average:={valuel+value2/2; writeln('Average is ',average:B:2);

Miscellaneous 359

0 Program E.2 program test(input,output);

(* Two compiler errors *)

var value:real;

begin

end;

writeln('Enter a value>>'); readln(value);

result:=sqrt(value); writeln('Square root is ',result:8:2);

0 Program E.3 program test(input,output);

(* Two compiler errors

var value, result:real;

begin

end;

writeln('Enter a value >>'); readln(value);

result:=sqr(value); writeln('Square is ',result:8:2);

0 Program E.4 program test(input,output);

(* Two compiler errors *)

var value:real;

begin

end.

writeln('Enter a value >>'); readln(value);

if (value<O) writeln('Can not calculate square root of a negative')

else writeln('Square root is ',sqrt(val) :8:2);

360 Mastering Pascal

0 Program E.5 program test(input,output);

(* Two compiler errors *)

var valuel,value2,largest:real;

writeln('Enter two values >>'); readln(valuel,value2);

if (valuel>value2) then largest:=valuel;

else largest:=value2;

writeln('Largest value is ',largest:B:2); end.

0 Program E.6 program test(input,output);

(* Two compiler errors *)

var valuel,value2:real;

begin

end.

writeln('Enter two values >>'); readln(valuel,value2);

if (value2>valuel) then begin

(* swap values *) temp:=valuel; valuel:=value2; value2:=temp;

writeln('Largest value is ',valuel:B:2); writeln('Smallest value is ',value2:8:2);

LJ Program E. 7 program test(input,output);

(* Two compiler errors *)

var valuel,value2:real;

begin writeln('Enter two values >>'); readln(valuel,value2);

Miscellaneous 361

end.

if (value2>valuel) then begin

(* swap values *) temp:=valuel; valuel:=value2; value2:=temp;

writeln('Largest value is ',value1:8:2); writeln('Smallest value is ',value2:8:2);

0 Program E.8 program test(input,output);

(* Two compiler errors *)

var value:real;

begin

end.

repeat writeln('Enter a positive value>>'); readln(value);

until (value>O)

writeln('Square root is ,sqrt(value));

0 Program E.9 program test(input,output);

(* Two compiler errors *)

var value:real;

begin

end.

repeat writeln('Enter a value between 0 and 100>>'); readln(value);

until (O<value>lOO);

writeln('Square root is ',sqrt(value));

LJ Program E.lO program test(input,output);

(* Two compiler errors *)

var value,ch:real

362 Mastering Pascal

begin

repeat writeln('Enter a value>>'); readln(value); writeln('Square root is ',sqrt(value)); writeln('Do you wish to continue>>'); readln (ch);

until (ch='n');

end.

CJ Program E.ll program test(input,output);

(* Two compiler errors *)

var i,sqr_value,cube_value:real;

begin

for i:=1 to 10 do begin

sqr value:=i*i; cude value:=i*i*i; writeln(i:8,sqr_value:8,cube_value:8);

end; end.

CJ Program E.12 program test(input,output);

(* Two compiler errors *)

var i:integer;

begin

end.

for i=1 to 10 do begin

end;

x:=10*i; y:=4*x+1; writeln(x:8:2,y:8:2);

CJ Program E.13 program test(input,output);

(* Two compiler errors *)

var value1,value2,result:integer;

Miscellaneous 363

function add values(a,b:integer) :integer; begin -

add:=a+b; end;

begin

end.

writeln('Enter two values>> '); readln(valuel,value2);

result=add values(valuel,value2); writeln('Added the result is ',result);

0 Program E.14 program test(input,output);

(* One compiler error *)

var valuel,value2,result:integer;

function add values(a:integer) :integer; begin -

add_values:=a+b; end;

begin

end.

writeln('Enter two values>> '); readln(valuel,value2);

result:=add values(valuel,value2); writeln('Added the result is ',result);

0 Program E.15 program test(input,output);

(* Two compiler errors *)

var invalue:real;

function get real(min,max:real) :real; begin -

end;

begin

end.

repeat writeln('Enter a value>> '); readln(val); if ((val<O) or (val>max)) then

writeln('INVALID'); until ((val>min) and (val<max);

invalue:=get real(O,lOO); writeln('Input value is ',invalue);

364 Mastering Pascal

LJ Program E.l6 program test(input,output);

(* Two compiler errors *)

var invalue:real;

procedure get real(min,max:real;var val); begin -

end;

begin

end.

repeat writeln('Enter a value>> '); readln(val); if ((val<O) or (val>max)) then

writeln('INVALID'); until ((val>min) and (val<max));

get real(O,lOO,invalue); writeln('Input value is 'invalue);

Miscellaneous 365

Index

lOMbps, 165 won, 57

-1-

-2-2s complement, 103, 331

8 80386,3

-A-AA, 189 Active, 148, 166, 167, 173, 186, 197, 199,

202,208,236,237,321 Address bus, 2, 158, 159 Algoritlun, 1,81,88 Ampersand, 282 ~.20,39,59,335,336

J\ngle, 18, 19,63,82,83,85,86 J\nimation, 123 ANSI, 8 APis, 243, 244 Apple, 14 Arctan, 16 Argument, 50, 51, 53, 78 Arguments passing, 226 Aritlunetic operator, 333 Arrays, 76, 77,85,87,92

indexing, 76, 116 strings,96, 100,102 structures, 116

Arrow keys, 136, 233 ASCII, 37, 40, 103, 104, 111, 148, 157,

168,169,172,179,180,182,195,206, 210,295,300 CR, 104, 111, 211 DCl, 170 DC4, 170 electrical characteristics, 165 LF, 104,111,211

366 Mastering Pascal

Assembly, 162, 163, 332 Assembly Language, 3 Asynchronous, 168, 169 Attributes, 224, 321, 322, 324 Averages program, 106 Averaging, 89

-B-Background colour, 128 Bar(), 128 BASIC, 1,3,230,231,232,237,259,

281,286,292 Baud, 169 Baud rate, 169 BCD, 154, 155, 195, 196 Best possible units, 28 BGI, 124, 125, 126, 129 Binary, 1,2,3,38,48, 103,108,109,162,

189,232,243,329-332,336 commands,3 data, 103 file, 103, 108, 109 numbers, 329 read/write, 108

BIOS, 140-149, 153, 154, 155, 156, 157, 160,185-187,201,213 equipment check, 145 keyboard, 147, 148, 156 printer, 149, 157, 185, 186, 187 reboot, 153 serial communications, 146 system time, 153, 154 system timer tick, 153 video interrupt, 143, 156

Bit shift, 336 Bitmapped, 103, 136 Bitwise, 208, 335, 336

operator, 335, 336 Black, 50,139,143,144 Black box, 50 Blank lines, 111 Blue, 139,143,144,156,251 BMP,235 Bold, 245

Boolean,38,39,41,57,59,64,255,294, 319,320,322,323

Boolean logic, 38, 64 Borland C, 230 Borland C++, 230 Bps, 147,165,169,207 Braces, 42 Brackets, 77 Buffer, 147,170-180,205,206,207,209-

212,321,322 Button,235,238,240,241,248,250-252,

266,267,271,294,295,297,298 Button settings, 248 Byte, 329

-C-CPrograrn, 78,80,103 C++, 230 Capacitive reactance, 15, 16 Capacitor, 15, 97, 117 Caption, 282 Caption property, 259,262,266,267, 270,

271,273,274 Carriage return, 104,182,186 Case Statement, 29 CD, 162,184 CD-ROM, 162, 184 Centigrade, 12,56,57,266,267 CGA, 125, 128 Character arrays, 92

Handling, 8 Strings, 113

Chdir(), 222 CheckBox,234,296 Circle(), 134 Click, 292, 296 Closegraph(), 127, 128 Coaxial, 165 COBOL, 1,3 Code

Machine, 2, 3 Object, 3 Source,3,4,5

Codes Feedback, 173

Colour, 29, 30, 31, 33, 34, 84, 85, 124, 126-132,139,143,144,156,232,236, 238,240,241,244,258,324

Colour code, 29, 30, 31 COM1:, 162, 167, 171, 174, 179, 199,

200,202,207,208,209 Combinational logic, 57

Combinations, 329 ComboBox, 235 COMMAND.COM, 221 Comments,5 CommonDialog,286 Compilation, 3, 4 Compile,4 Compiler, 3, 4, 5, 8, 9, 116 Compiler resource file, 232 Compiling, 3 Complex arithmetic, 118 Complex number, 18, 63, 85, 86, 118,

121, 122 Components, 232 Compressed, 103 Compression, 244 Computer architecture, 2 Connectors, 166, 167 Constants, 5, 29, 79 Control bus, 2 Control Panel, 160, 171,200 Copper, 6 Copper wire, 6 COS,228 Cosine, 63, 101, 318 Counting characters, 95 Counting the number of characters, 95 CR, 104, 111,211 Creating a menu system, 283 CRT, 144, 153, 187, 193, 218 CTS, 167, 170, 173 Current, 12, 46, 83, 104, 235, 273, 274,

275,276,278,297,299 Cursor, 4, 11, 126, 143, 144, 155, 182,

320,321,322,323

-D-DAT, 106, 107 Data,2,6, 7, 10, 11,36,50,52,53,54, 76,

79,90,92,96, 103,104,109,113,114, 115, 119, 120, 140, 142, 143, 146, 147, 159,160,165-175,179, 184-186,188, 189,192,197-199,201,205,207,209, 214,215,224,227,228,233,234,243, 244,329

Data bus, 2 Data Register, 162, 163 Data type, 6, 50, 52, 53, 76, 92, 96, 104,

113,114 Database, 96, 114, 119, 121 Database program, 114, 121 Date, 152, 156, 213, 214

Index 367

Date and time, 140, 198, 213, 215, 216, 217,322,324

DateTime, 215 DB25S, 166 DB9S, 166 DCE, 166, 167, 173 Debugger,4 Decimal, 7, 11, 12, 37, 45, 46, 48, 49, 111,

151,195,329-333,336 Declaration, 7 Declaration of variables, 7 Degrees, 16, 17, 19, 41, 60, 61, 101, 228,

279 Del, 153, 201, 282, 321 Delphi, 230--237, 243, 244, 256, 257, 258,

259,265,279,280,281,286,289,290, 292,301,302

Delphi Events, 292 Delphi files, 231 Delphi Input/Output, 243 Digital, 39, 162 DIR, 222 Disk drives, 2 Divide by zero, 23, 27, 44, 46, 107, 280 Divide error, 141 Division, 333 Do .. while(), 42, 43 DOS, 141, 142, 144, 147-153, 155, 156,

187,188,204,214,218,220,221,230, 318,319,322,323

DOS services, 142, 149 Drag and drop, 299 DSR, 167,170,173 DTE, 166,167,171,173 DTR, 167, 170, 173

Earth, 14 ECP, 184 Edinburgh, 259

-E-

Edit, 3, 233, 234, 261, 266, 271, 283, 284, 285,290,296

Editor, 3, 4, 103, 106 EEPROM, 1 EGA, 125, 126, 128, 129, 160 ElA, 165 Electromagnetic, 24, 28 EM spectrum, 24 EM wave, 24, 25,28 EPP, 184 Equivalent resistance, 7, 9, 17, 34, 35, 81,

82

368 Mastering Pascal

Error,8,9,23,27,46,63,94, 127,129-135, 137, 141, 142, 147, 149, 155, 157, 168,174,182,183,186,187,209,222, 223

Error control, 168 Error detection, 168 Esc, 211 Event-driven programming, 230 Events list, 238 Executable, 3, 4, 8, 103, 221, 226, 246 EXP,228 Exp(), 53 Exponent, 104

-F-Fahrenheit, 12, 56, 57,266,267 Farads, 15 File

binary, 103 binary read/write, 108 pointer, 104 text, 103, 106, 111

File 1/0, 103 Find_nearest_pref{), 83 Firmware, 1 Floating point, 6, 7, 98, 104, 106, 107,

108,111,113,114,331 Flow control, 171 ForLoop,36,38,48,59,85, 100 Force, 14, 15 Force of attraction, 14 Form window, 236, 237 Forms,232,235,244,245,246,250,255,

258,259,265,266 Forms and code, 259 FORTRAN, 1, 3, 103 Fourth,40,81 Frame, 168 Frame format, 168 France, 259 Frequency, 15, 16,24,25,28,98,99, 176,

179,180,181,205,207,229 Function header, 50, 51, 54, 55, 78,255 Functions,8,50--52,54,55,56,57,59,

60,62-64, 77,90,92, 105,116,123, 126, 129, 140, 141, 149, 152, 155, 158, 211,220,228,240,243-245,315,318

-G-Gateways, 158 Generating software interrupts, 142

~_flo~,l01,116 ~_int(), 116 ~_values(), 78, 80, 106 Getimage(), 127, 136 ~. 127,129 ~). 127, 129 GIF, 103 Global variable, 54, 55 Cd1Klient, 13,62, 78,82,280 Grapherrormsg(), 129 Graphical user interface, 123 Graphics, 123, 125, 129-131, 133-135,

137,143,162,241,243-246,250,255, 265

Graphics drivers, 124, 125, 129 Graphics routines, 123, 126 Ground, 166, 167, 173, 185, 189 GroupBox, 235 GUI, 123

-H-Fland~g. 170,171, 172,173,178,

184, 185, 186 Hardware, 1, 2, 3, 128, 129, 140, 160,

170,172,197,198,220 handshaking, 170, 172 interrupts, 197

Help files, 103 Hertz, 15 Hexadechna1,48,49,332,333 Hierarchical decomposition, 51 High-level language, 3 Hobby computers, 1 Hz, 98,99

-I-110

digital, 162 inputting a byte, 162 isolated, 158, 160 memory mapped, 158, 159 outputting a word, 163

110 addressing, 188 110 port, 162, 163 IBM, 184 IDE,l62 IEEE, 184 If Statement, 20 ~),20,21,22,24,29 lf ... else statements, 20 Image,235

Images, 123, 235 Impedance, 97 IMR, 203, 205, 206, 207, 208, 209 Infonnation,2,3,98,103, 123,124,149,

235,243,248 Initgraph(), 129 Initializing graphics, 129 Input/output, 2, 8, 10, 11, 50, 105, 140,

152,158,243 Integrated development, 4 Intensity, 322 Interface, 50, 158, 162,230,231,232,259 Interfacing, 158, 159, 192 Interfacing with memory, 159 Interrupt service routine, 140, 197, 198,

208,209 Interrupt vectors, 141, 160, 199

DtQO, 141,199-204,213,218,219 DtQ1,141,199-201,204 DtQ2,141,200-202,204 DtQ3,141, 199-201,204 DtQ4,199,200-202,204,206,207,

208,209 DtQ5,199,200,202 DtQ6,200,202,204 DtQ7,141,199,200,202,204 DtQ9, 200-202

Isolated 110, 158, 160 ISR,140, 141,153,197,198,199,208,

209

Java, 103 JPEG, 103

Kn,28

-J-

-K-

Keyboard, 1, 2, 3, 8, 10, 11, 161 KeyPress, 292, 293, 295, 300 Keywords, 3, 7, 20, 114

-L--Label,234,258,266,270,271,273,274,

277 Lambda, 24, 25 LCR,174,175,177-181,205,207 LED, 192 Len~,31,32,33,92,94,95 LF, 104, 111,211

Index 369

Libraries, 3, 8, 50, 123 Library, 8, 286 Light, 5, 24, 25, 143, 144 Limiting ranges of inputs, 43 Line(), 131 Linker, 3, 4 Linking,3,243 ListBox, 235 Ln(), 53 Local variable, 50, 54, 55, 77, 86 Log(), 53 Logarithms, 53 Logical, 20 Logical operator, 59, 334, 335 Long integer, 104 Long word, 329 Lowercase, 32, 34 LSR, 174-176,179,180,181,205,206,

210

-M-Mn,28 Machine code, 2, 3, 158 Macros, 3 Main Menu, 234 Manganese, 32 MathernaticalfUnctions,8 Memo, 234, 287 Memory, 1, 2, 4, 7, 116, 128, 136, 141,

153, 158, 159, 160, 161, 162, 170, 185, 188,222,230,323,329

Memory address, 1, 2 Memory map, 158, 159, 160, 161, 162 Memory mapped 1/0, 159 Menu,4,35, 100,121,233,236,238,240,

282-284,287 Menu bar, 233 Menu editor, 281,284 Menus, 243, 281 Microprocessor, 1, 2, 3, 159 Microsoft, 103, 123, 141, 159, 160, 200,

220,230,243,286 Microsoft Visual C++, 230 Microsoft Windows, 123, 141, 159, 160,

200,220,230,243,286 Microwaves, 24 Modern connection, 178 Moderns, 169 Modular program, 50 Module, 76, 77, 85, 86 Motion video, 103 Mouse Down, 296

370 Mastering Pascal

Mouse Up, 296 Multidimensional arrays, 85 Multimedia, 244 Multiple choice example, 259 Multiplexing, 184 Multiplication, 333

-N-Negative, 52, 331 Negative numbers, 331 Nested loop, 59 Network, 244 Nibble, 329 NOR,39 }ff, 103,171,220,230,243 Numbers and representations, 331

-0-Object code, 103 Object Inspector, 234, 236, 237, 238, 252 Object properties, 258 Objects,232,234,277,278,284,293 Octal, 45, 46, 332 OLE, 243, 244 Open _graphics(), 130 Operating system, 10, 103, 140, 214, 220,

221,230,243,322,323,324 OR, 20, 59, 137, 190, 334, 336 Ordered, 121 Outtextxy(), 132

-P-Packing Time, 215 Parallel, 7, 9, 17, 19, 25, 26, 34, 35, 44,

80,81,97,98,99, 100,145,157,162, 165, 167, 184, 185, 186, 188, 189, 191, 193,195,199,202,229

Parallel port, 157, 162, 165, 167, 184, 188,189,191,193,195,199,202 data handshaking, 185, 186 PC connections, 185

Parallel ports, 184, 188, 199 Parallel resistance, 19, 25, 26, 34, 44, 80 Parallel resistors, 9, 17, 19, 35 Parallel_irnpedance(), 98 Parameter list, 77, 76, 78 Parameter passing, 50, 76, 83, 84 Parameters, 14, 31, 50, 51, 62, 76, 82, 93,

98,99, 101,143,146,169,171,175, 207,220,221,226,295

Parity, 168, 183 Pascal

array routines, 93 arrays, 76 compilation, 4 constants, 5 file I/0, 105 functions, 51, 315 parameter passing, 76 program,5, 7-9, 11,55,56,57,59,60,

96, 105, 106, 108, 109, 114, 115 string conversion routines, 94 string, 92, 94 structure,5,22, 79,81,83,98,116 variable declarations, 7

Passing arrays to functions, 77 Passing by reference, 51 Passing by value, 51 PC, 3, 4, 103, 123, 124, 141, 153, 159,

160,161,167,174,184,185,198,202, 203, 213, 230

PC connectors, 167 PC graphics, 123 Permutations, 38, 59 PIC, 197,200,202,203,205,208 Pixel, 123, 128, 130 Pixels, 123, 124, 129, 130, 132, 139 Pointer, 95, 104, 234 Pointers, 51, 78, 80 Popup menu, 234 Port number, 146, 147 Postscript, 103 Power(), 53 Precedence, 336 Preferred resistor value, 87, 88 Preferred values, 82 Print_results(), 79 Priority, 337 Procedures, 52, 76, 77, 78,86,90,92,

120,143,210,213-215,222,244,265, 283,314,315,320

Processor interrupts, 142 Project file, 232, 266 Project files, 232 Project window, 235, 236 Properties list, 238 Putimage(), 128, 136 Putpixel(), 130

-Q-Quadratic,21, 78,80,270,271,291

Quadratic equation, 21-24,28, 76, 78-80, 270,271

Quadratic roots, 270

-R-Radians, 16,19,60,61,228,279 Radio, 24, 232, 235, 241 RadioButton, 235 RadioGroup, 235 RAM,2, 160 Randomize(), 130 Range, 1,6, 7,44,64,82,89, 160,238,

272,273,281,331 RC circuit, 37, 97 RD, 167,171,173,177,178,179,205,

207 Reading and writing one character at a

time, 109 Readln(), 100 Real-time, 154, 155, 212 Records, 113 Records in Pascal, 113 Rectangular, 121 Red, 139, 156, 251 Register, 162, 163 Register addresses, 1 77 Relationship operator, 334 Repeat... until, 36, 42, 43, 48, 93, 105 Repeating program, 43 Resistance, 6, 7, 9, 12, 17, 19, 26, 28, 31,

32,34,35,43,44,46,47,80,81,82, 83,84,88,98,99,274,275,276

Resistance calculation, 272 Resistance of a conductor, 31 Resistivity, 31 resistor colour bands, 30, 139 resistor colour code, 29 Resistors, 17, 29,84 Resize, 293, 300 resolution, 123, 124, 128, 132 return value, 52, 250 RL series, 100 RL series circuit, 16, 60, 100 R0~,2, 140,160,162,184 root,22,23,27,44, 76,78-80,270 root type, 78-80 RS-232, 165, 166, 167, 168,169, 171-

174,178,204,207,208 communications between nodes, 169 electrical characteristics, 165 frame format, 168 line voltages, 165

Index 371

setup, 171 RTS, 167,170, 173 Running average program, 79

-8-Sampling, 89 Schematic, 15, 17,38,57,58,59,97 ScrollBar, 235, 273, 274 Search, 110,289 Sectors, 150 Segment, 141 Seriw, 141,142,174,178,200 Seriw communications, 146, 165, 167,

174, 188 Setcolor{), 126 Shape, 137,235 Signed integer, 6, 114 Silver, 32 SIN,228 Sine,41,60,61,63, 101,226,227,320 So~are, 1,2,5,6,92, 123,140-142,

159, 170, 171, 178, 184, 197, 198, 218, 323

So~are handshaking, 170, 172 So~are Interrupts, 140, 142, 198 Sort(), 81 Sorting program, 81 Sound, 103,198,199,202,244 Sound file, 103 Source,3,4,5, 15,93, 134,135,232,299,

322,323 Specification, 1 Speed oflight, 5, 25 Speedbar, 233 Square root, 23 Squares, 40 Standard functions, 8 Start bit, 168 Statement block, 20, 21, 36, 42,43 Statements, 335 Statements

Logical, 20 Stop bit, 146, 147, 168, 169, 171, 175,

179,205,207 Straight line, 13, 62, 78, 82, 280, 291 Strings,92,93,96,98, 100,102,113,226,

318 Structure chart, 52, 53, 79, 80, 81, 83, 97,

98, 116 Structures, 116

arrays, 116 dot notation, 114

372 Mastering Pascal

members, 113, 114 SVGA, 125, 126, 129 Swap, 77,78 Swapped, 81 Switch statement, 29 Switch(),29 Synchronized, 2, 168, 232 Synchronous, 162 Syntax, 163 System cwls, 220 System Commands, 220 System(), 221

-T-TAN,228 Tan function, 55, 318 11), 167,171,173,177,178,179,205,

207 Temperature conversion, 268 Temperature conversion program, 266 Terminw, 167,170,207,211 Terminator, 5 Tem,4, 13-15,18,23,28,33-35,52,53,

56,59,87, 107,108,119,268 Text, 103, 143, 247, 254, 258, 261,266,

271,286,288,297,298 Text editor, 103, 106 Text file, 103 Text keyword, 105 Textbackground function, 33 Ticker timer, 142 Time, 142, 182, 183, 213, 214, 215, 216,

225,322,324 Time step delay, 89 Timer ticks, 218 Truth table, 38, 39, 41, 57-59, 335, 336 Turbo Pascw, 3, 4, 5, 6, 7, 8, 123, 142,

143,153,162-165,189,204,213,220, 226,314,315,318

Twimed-pair, 165 Type keyword, 77, 114 Types of roots, 23,270

-U-Unit files, 232 UNIX,220

more, 76 Unload, 293, 300 Upcase, 26

-V-V ar keyword, 77, 78 Variables, 50-52, 59, 77, 78, 79, 80, 81,

76,86,98 Velocity, 44,45 Version, 150, 155,243, 318 VGA, 125, 126, 128, 129, 160 Video, 103, 124, 129, 141, 143, 145, 156 Video driver, 124 Visible, 24 Volmge, 12, 15,46,47,273,274,275,

276,278

-W-Wavelength, 24, 25, 28

While(), 42 While/Repeat Loops, 42 White, 126 Win32,243 Windows 3.x, 243 Windows 95, 103, 141, 159, 160, 171,

200,220,230,243 Windows NT, 103, 230, 243 Windows NT/95, 1, 10, 20, 29, 171, 338 Windows sockets, 244 WMF,235 Word, 329 Word processor, 103 Words, 36, 95, 101, 110

Index 373