Turbo Pascal Tutor 4.0 Help File+:

   çTodaH/╩L!µ(z)5,╓015≡3╬=j>Aµ@ÑFG/vLÿReS@W╞[S\+≡_▄dje,∩h▐mun,Ωpy√yA░{ÿÄdÅî
¬ôó╩óv4Ñ÷»╖░f

┼╢4├─u╬┼*╥⌐╥h╒7▀╔▀W6π\∞$φF	
Ñ⌡{ⁿG²:`Γd	6¥
à=╧LF╧*+úY-█3¥4AL6π=∩>CXAL╛LQ'PX¥X2ªZe╝edúgçt@u`$Welcome to the Turbo Pascal Tutor!KThis program supplements the Turbo Pascal Tutor manual. It has 28 differentDexamples that let you experiment with many Turbo Pascal concepts andGconstructs. Once you've read about a topic in the manual, run the TUTORIprogram, choose the corresponding example from the menu that appears, andexperiment with the example.Each example has 3 components:I  (1)  A window of introductory text and instructions (select any example       and press F1)K  (2)  An interactive program that lets you enter values from the keyboard,I       inspect the values of variables, step through code or select items       from a menuD  (3)  A multiple choice quiz (select any example and press Alt-Q)Special Keys────────────KSome of the keys on the keyboard have special meanings while the program isKrunning. Get in the habit of looking at the bottom line of the screen for a/quick description of what "hotkeys" are active.Using the Menus───────────────@The keys that control movement through the menus are as follows:+─┘  Selects the item that is highlighted8    Moves the highlight bar to the previous menu item4    Moves the highlight bar to the next menu itemHHome Moves the highlight bar to the first menu item in the entire menuHEnd  Moves the hightlight bar to the last menu item in the entire menu,PgUp Moves the highlight bar back one page/PgDn Moves the highlight bar forward one pageJESC  When not in an example, this key will take you back to the previous
     menu.Using the Examples──────────────────FThe examples assume that you have read the sections of the manual thatpertain to them.KThere are two types of examples.  The first type of example has a menu. TheFchoices in the menu allow you to run a function, procedure, or section4of code, or modify a variable that the example uses.KThe second type of example allows you to step through some source code that0demonstrates how a particular contruction works.KWhen you first look at an example, press the F1 key for help if you don'tknow what to do.  Getting Help  ────────────L  The Help screen provides information about running the example, as well asA  information about the subject of the example. For instance, the  Taking a Quiz  ─────────────J  If you're curious to see how much you remember of the information in theM  manual and the Help text, press Alt-Q when you're in an example to take a
  short quiz.  Reading in Values  ─────────────────L  Most of the examples will allow you to enter information to initialize theG  example variables.  When entering non-real numbers, you can enter the$  number in three different formats:I  Decimal -- Type the number as you would normally (example: 34, -56, 0).H  Hexadecimal -- Preface the number with '$' (example: $95, $FFFF, $AE).C  Binary -- Append a 'B' or 'b' to the number (example: 10101010B).F  When using real numbers, you can enter them in the decimal format orK  in scientific notation format (example: 2.876, 1e20, -1.34e+6, 2.523E-3).  Other Notes
  ───────────L  When a variable is being updated it will blink.  To speed up this process,E  press any key when the blinking starts. The variable (and any other@  variables that are being updated) will be updated immediately.  Special Options  ───────────────H  In the variable window of each example, values are always displayed inK  decimal notation. For more advanced users, it is also possible to displayE  hexadecimal and binary values along with the memory address of eachM  variable. For more information, bring up the Options menu (located on theG  main menu) and toggle the third menu selection (Hex/binary values).Changing the Options────────────────────JOne of the choices on the Main Menu is "Options." This part of the programIlets you customize aspects of the program.  In the Options menu there arefour menu items:D  o The first choice, "Install colors," is used to modify any of the,    program's colors to suit your own taste.K  o The second choice, "Wait for snow," is used to control snow checking onK    your display adapter. Old CGA adapters tend to display interference (orJ    "snow") on the screen when the screen is written to directly. The snowL    checking will get rid of the snow with a corresponding loss in execution
    speed.F  o The third choice, "Hex/binary values," is turned on if you want toI    display example variables in a more detailed format that includes theJ    variable's memory address, along with its value in decimal, binary and    hexadecimal notations.F  o The last choice, "Save options," is used to permanently record theI    current options inside the TUTOR.EXE file. After this choice is used,G    the current options will be saved as the program's new defaults and8    will be present every time you start up the program.
The Example───────────HExperiment with the different functions.  Look at the results of integerGoverflow by trying Inc(32767) or 10000 * 10000.  Look at the results ofGinteger underflow by trying Dec(-32768).  See what happens when you tryto div a number by 0.
Information───────────IPascal integers are whole numbers, that is, values without a fractionalFcomponent. For example, 5, 0, and -2209 are integers, but 13.5 is not,Abecause it has a decimal point and an associated fractional part.GIntegers have a limited range: They can't be greater than 32767 or lessIthan -32768. Using integers rather than reals to store numeric valuesEresults in efficient programs because your computer's 8086-family CPUFcan work with integers quickly; furthermore, they require only 2 bytesof storage."   Program IntegerVsRealSpeedTest;   uses Crt;   var     I : integer;     R : real;   begin     I := 0;     R := 0.0;0     Write('Press Enter to start Real loop...');     Readln;     while R < 30000.0 do       R := R + 1.0;     Writeln('Done');3     Write('Press Enter to start Integer loop...');     Readln;     while I < 30000 do       I := I + 1;     Writeln('Done');"   end. { IntegerVsRealSpeedTest }FThe LongInt (long integer) numeric type has a much larger range than>type integer, all the way from -2,147,483,648 to 2,147,483,647C(roughly +/- 2 billion). Long integers are handy in situations thatBrequire speed, but need more range than that afforded by integers..Long integers require 4 bytes of storage each.Integer DivisionHTo divide two integers, use the DIV operator rather than /, the realdivision operator.OverflowFWhen using integer variables, be on the alert for overflow problems.GOverflow occurs when a calculation performed on two integers produces aFvalue too large to be stored in the space reserved for the result. For(example, consider the following program:   program Overflow;   var     A,B,C: integer;   begin     A := 1000;     B := 1000;     C := A * B;     Writeln(C);   end. { Overflow }ABecause 1,000,000 doesn't fit in the 2-byte space allotted for anEinteger, C gets the mysterious value 16960 (16960 equals the lower 16Fbits of 1,000,000 when expressed in binary), and no error is reported.KThis example demonstrates some of the operations that can be performed on \3integers. The variable declarations are as follows:var  X, Y, Z : integer;
10 DIV 3 =3.33431DIV performs integer division
10 MOD 3 =3.334313MOD calculates the remainder after integer division$10 =102016324In a hex number, each digit represents a power of 1610 =$10$A0$0A$016Hexadecimal digits include 0 through 9 and A through F5How many bytes are used to store an integer variable?123#Depends on the value of the integerBAn integer can represent 64K different values; 64K = 2 to the 16th0Integer overflow is trapped by the $R+ directiveTrueFalseH$R+ turns on checking for subrange type assignments and array subscripts
The Example───────────LSince this example mainly shows different methods of bit manipulation, it isCmore instructive if you have the "Hex/binary values" setting set toC"Show."  To change this setting, go into the "Options" section fromLthe Main Menu.  Move the highlighted bar to the selection called "Hex/binary!values," and press the Enter key.
Information───────────KLike integers, words are 16-bit (2-byte) memory objects. Unlike integers,Lwhich can be either positive and negative, variables of type word are alwaysIpositive and are used in situations where negative values aren't neededLor where a variable represents a bit pattern rather than a value.  The value$of a word can range from 0 to 65535.LTurbo Pascal provides numerous operators for manipulating words. Most have aKdirect expression in 8086 machine language and are therefore performed veryquickly.LThe AND, OR, and XOR operators take 2-word operands and produce a wordHresult by performing the appropriate Boolean operation on each of the 160bit pairs. For example, where A and B are words:&   A = $5555 = 0101010101010101 binary&   B = $00EF = 0000000001111111 binaryL   A AND B = set bits that are on in both A and B   = 0000000001010101L   A OR  B = set bits that are on in either A or B  = 0101010101111111J   A XOR B = set bits that are different in A and B = 0101010100101010DThe NOT operator complements (flips each bit) of its word operand:"   NOT B = 1111111110000000 binaryIThe SHL/SHR (shift left/shift right) operators slide the bits in a word5to the right or left, shifting in zeros as necessary.$   A SHL 2 = 0101010101010100 binary$   B SHR 5 = 0000000000000011 binaryNThe Hi and Lo functions return the high- and low-order bytes, respectivelyof their word parameters:   Hi(B) = 00000000 binary   Lo(B) = 01111111 binaryFThe Swap function reverses the high- and low-order bytes of its word!parameter and returns this value:$   Swap(B) = 0111111100000000 binaryKThis example demonstrates some of the operations that can be performed on \0words. The variable declarations are as follows:var  X, Y, Z : word;	1 XOR 1 =10EThe XOR logical operator produces a 1 when its operands are different1 OR 0 =10?The OR logical operator produces a 1 when either operand is a 1	1 AND 0 =10CThe AND logical operator produces a 1 only when both operands are 1NOT 1 =10(The NOT operator complements its operandNOT $0F0F =$FFFF$0000$FF00$F0F0(The NOT operator complements its operand
$FFFF SHL 4 =$FFFF$0000$FFF0$F0F0SHL = "shift left"Hi($0FFF) returns$000F$00FF$FFF0$FFFF.Hi returns the most significant byte of a wordSwap($1234) returns$4321$34121234$3434ISwap returns a value equal to the low-order and high-order bytes reversed
The Example───────────ITry the different functions to see what they do.  See how chars and bytesGcan be converted back and forth.  Find out what happens when you try to2increment character 255, or decrement character 0.
Information───────────GVariables of type char are designed to hold ASCII codes, that is, aEnumber that stands for a particular textual character. Each is a byte@long and represents a single printable or control character. Forexample:   var     C : char;     N : integer;   begin     .     .     .     C := 'A';GIt can be useful to get at the underlying numeric value of a character;2this operation is performed by the Ord function:     N := Ord(C);HSimilarly, it is often useful to turn an ordinal value into a character;2this operation is performed by the Chr function.!     C := Chr(33);    { C = '!' }JArrays of characters are such useful structures that Turbo Pascal provides(the string type for working with them.   program CharDemo;   var     C : char;     J : byte;   begin
     J := 50;     C := Chr(J);     Writeln(C);     J := Ord(C);     Writeln(J);     C := 'A';     J := Ord(C);     Writeln(J);     C := Chr(2);     Writeln(C);   end. { CharDemo }KThis example demonstrates some of the operations that can be performed on \5characters. The variable declarations are as follows:var  C1, C2, C3 : char;  X : byte;:How many bytes does it take to store a character variable?123%Depends on the value of the character2A character variable can have 256 different values4Which of the following return a result of type char?Pred, Succ, ChrPred, Succ, SqrtPred, Succ, OrdAll of the above.Chr(65) = 'A'; Sqrt(65) = 8.06; Ord('A') = 65;Chr(Ord('A')) = 'A'TrueFalseDOrd converts from char to integer; Chr converts from integer to char*Executing:  Write(Chr(1));  prints out '1'TrueFalseWrite(Chr(48)) prints out '0'What does UpCase('/') return?' ''/'It causes a runtime errorA random characterUpCase only affects letters
The Example───────────FTry out the different functions to see what they do.  See what happens%when you try to divide a number by 0.
Information───────────HA real is a number that can (but doesn't have to) contain a fractionalDpart. Examples include 1.5, -0.33335, and 1.987E3. (The last exampleFis in so-called exponential (or scientific) notation, and is read as"1.987 times 10-to-the-3rd.")JTurbo Pascal variables of type real (also called floating-point numbers)Ihave a vast range--all the way from 1.0E-38 (a number very close to zero:I0.00000000000000000000000000000000000001) to 1.0E+38 (an enormous number:I100,000,000,000,000,000,000,000,000,000,000,000,000). Real numbers can be9positive or negative and require 6 bytes of storage each.Accuracy LimitationsIUnlike integers and long integers, Turbo Pascal's internal representationEof reals is not exact. For one thing, no number is known to more thanBeleven digits of accuracy. For example, 123,456,654,321 would beCrepresented as a real as 1.234566543E+11 (123,456,654,300; the last"two digits of precision are lost).DFurthermore, because of the internal scheme used to represent reals,Amost decimal fractions, even those with fewer than eleven digits,=cannot be represented exactly. For example, $1.49 can only beBapproximated by a real. That approximation is very good (somewhere>between $1.489999999 and $1.490000001), but lacks the absoluteprecision of integers.DTurbo Pascal offers three additional floating-point types--double,Jextended, and comp--that offer more range and accuracy than type real,Ewith an accompanying trade-off in storage requirement and calculationHspeed; these types can be used only when an 8087 or 80287 coprocessor isFavailable. See the Turbo Pascal manual for information on these types.Formatting Reals>To output a real in a format other than the default scientific<notation, use "write parameters"; two integers of formattingBinformation included after a real expression in a Write or Writelncall. For example:  Writeln(R:12:2);>outputs real variable R in a more-standard decimal form (right?justified in a field 12 columns wide, with two digits after thedecimal point).   program RealAccuracyDemo;   var
     R: real;   begin?     R := 12345654321.0;       { reals have 11-digit accuracy }     Writeln(R:15:0);3     R := 1234567654321.0;     { a 13-digit value }     Writeln(R:15:0);3     R := 123456787654321.0;   { a 15-digit value }     Writeln(R:15:0);   end. { RealAccuracyDemo }KThis example demonstrates some of the operations that can be performed on \7real numbers. The variable declarations are as follows:var  X, Y, Z : real;6Which of the following is NOT a constant of type real?2.50300001E200.45e-238Integer constants are whole numbers from -32767 to 32767?What data type results when an integer is multiplied by a real?integerreallongintdouble100 * 0.5 = 50.0;How many bytes are used to represent variable of type real?2468!Depends on the size of the numberType double requires 8 bytes'The statement: Write(15.123:0) outputs:01515.1231.5E+01FDefinition of real write parameter:  <real>:<field-width>:<dec-places>Write(15.123:0:0) outputs:01515.1231.5E+01FDefinition of real write parameter:  <real>:<field-width>:<dec-places>
The Example───────────AExperiment with entering different characters to see how the code	executes.
Information───────────IThe IF statement evaluates a Boolean expression to determine which ofHtwo possible courses of action to take. It optionally includes an ELSE!clause. Its syntax is shown here.     IF <boolean-expression> THEN       <statement1>    [    ELSE       <statement2>    ]KIf <boolean-expression> evaluates as True, then <statement1> is executed;Kexecution then continues with the next statement after the IF statement. IfH<boolean-expression> evaluates False, then <statement1> is skipped and<statement2> is executed.BNote that <statement1> and <statement2> can be compound statements1(begin/end blocks), or even another IF statement.<Confusion inevitably arises over IF statements and semicolonDplacement. It may help to remember that ELSEs are considered part ofGthe IF statement that immediately precedes it; they aren't statements?in their own right. Since the compiler interprets semicolons asBstatement separators, it doesn't make sense to have one inside aDstatement--and that's just what you're doing if you put one directlybefore an ELSE.   program IfDemo;   var     a,b: integer;   begin)     Write('Enter values for A and B: ');     Readln(a,b);     if A > B then?       Writeln('A is greater than B')     { no semicolon here }	     else/       Writeln('A is less than or equal to B');   end. { IfDemo }MThis example demonstrates how IF statements work. The variable declarations \are as follows:var  C : char;if not false then ClrScr;The screen will be erasedThe screen will NOT be erasedIs not a legal Pascal statement*not false = true; ClrScr clears the screenif 0 = true then ClrScr;The screen will be erasedThe screen will NOT be erasedIs not a legal Pascal statement8Can you compare apples (integers) to oranges (Booleans)?Which expressions are true?1 AND 1 = 1
1 OR 1 = 11 XOR 1 = 0All of the above@true AND true = true; true OR true = true; true XOR true = falseA semicolon:Always precedes an ELSE clauseNever precedes an ELSE clause!Sometimes precedes an ELSE clauseCSemicolons separate statements; they don't appear inside statementsGThe statement: if a>b then begin a := a-1; b := b-1 end; else a := a+1;Is a valid Pascal statement1Is incorrect because a semicolon proceeds an else?Is incorrect because no semicolon separates  b = b-1  and  end;CSemicolons separate statements; they don't appear inside statementsKIn the statement:  if a>b then begin a := a-1; b := b-1; end else a := a+1;7The semicolon after b = b-1 is unnecessary but harmless9The semicolon after b = b-1 makes the statement incorrect(The semicolon after b = b-1 is necessary7End doesn't require separation from previous statementsJGiven: a=1 : if a=3 then a:=2 else if a=2 then a:=3 else a:=2;   What's A?123AAn ELSE clause is always associated with the nearest IF statement
The Example───────────AExperiment with entering different characters to see how the code	executes.
Information───────────EThe CASE statement allows a program to test the value of an ordinal>variable against a number of possible values, and to execute/statements appropriate for each possible value.  CASE <ordinal-expression> OF    <value1> : <action1>;    <value2> : <action2>;    .    .    .    <valueN> : <actionN>;  [    ELSE <actionN+1>;  ]  END; { case };Note that the ELSE clause is optional; if omitted, and ifG<ordinal-expression> matches none of the values in the case-tests, then<execution simply continues with the statement after the CASE
statement.ACASE statements usually result in more readable programs than the9equivalent operation performed by multiple IF statements.   program CaseDemo;   uses Crt;   var     command: char;     foreColor,     backcolor: integer;   begin     foreColor := 0;     backColor := 0;     while true do
     begin7       Write('T(one, F(orecolor, B(ackcolor, Q(uit: ');       command := ReadKey;       Writeln;"       command := UpCase(command);       case command of         'T': Write(^G);         'F': begin+                foreColor := foreColor + 1;%                TextColor(foreColor);               end; { 'F' }         'B': begin+                backColor := backColor + 1;*                TextBackground(backColor);              end; { 'B' }         'Q': Exit;
         else%           Writeln('Illegal command')       end; { case }	     end;   end. { CaseDemo }HThis example shows how CASE statements work. The variable declarations \are as follows:const  Number = 'Number';  Upper = 'Upper case';  Lower = 'Lower case';  Special = 'Special';var  C : char;?Which of the following types cannot be used as a CASE selector?booleancharintegerstringCASE selectors must be ordinal=The statements after a CASE statement's optional ELSE clause::Are executed whenever there's a match of a previous clauseAre never executed=Are executed whenever there's no match of any previous clauseAStatements in the ELSE clause are intended for the default action@What happens if the CASE expression matches nothing in the list?;Nothing; execution simply continues with the next statementBThe operation of the CASE statement is undefined in this situation-In standard Pascal, this condition is illegalAHow many values are allowed in a CASE statement's list of values?10025665536Variable, limited by memory2CASE statements are sometimes too large to compile@Can subranges be used in the list of values in a CASE statement?YesNo4The value "1,5,7..10:" is legal in a CASE statement.
The Example───────────DTry different combinations of Strt and Stop to see the effect on theEexecution of the loop.  What happens if Stop < Strt?  If Stop = Strt?
Information───────────BThe FOR loop is for situations in which a statement or series ofFstatements must be repeated 0 or more times--the exact number of timesIbeing known before the loop begins. In contrast, loops based on the WHILEKand REPEAT/UNTIL statements are better suited to circumstances in which theKterminating condition must be calculated in the loop (that is, in which the2number of times to repeat isn't known in advance).Syntax:A   FOR <ordinalVar> := <ordinalExpr> {TO|DOWNTO} <ordinalExpr> DO     <statement>AFor example, this loop outputs 'Hello' ten times (N is an integer
variable):   for N := 1 to 10 do     Writeln('Hello');GThe DOWNTO keyword causes the counter variable to be decremented witheach pass, as in this program:   program ForDemo;   uses Crt;   var     N : integer;   beginE     Write('Intercepted at midfield by Crazy Legs Kahn!  He''s at ');     for N := 10 downto 1 do
     begin$       Write('the ', N*5,' . . . ');       Delay(400);	     end;     Writeln('Touchdown!');  end. { ForDemo }DThis example shows how a FOR loop works. The variable declarations \are as follows:var  I : integer;  Strt : integer;  Stop : integer;/Which of the following is true about FOR loops?,A FOR loop will always execute at least once-The index variable is always incremented by 1A FOR loop can be infiniteNone of the above2This is a legal FOR loop:  for i := 10 downto 1 doEWhat variable type CANNOT be used as an index variable in a FOR loop?integerbyterealchar(The index variable must be a simple typefor i := $01 to $100 do;Will execute 100 timesWill execute 256 timesIs not a legal Pascal statementNone of the above3$100 is a hexadecimal constant equal to 256 decimalThe loop: for i := i to i do;Will execute 0 timesWill execute 1 timeIs not a legal Pascal statementNone of the above;The bounds of a FOR loop must each be an ordinal expressionGWhat is the value of the control variable after a FOR loop is finished?	UndefinedThe last value it hadThe last value it had + 1=The control variable is incremented if the loop will continue
The Example───────────HTry different combinations of I, Limit, and Add to see the effect on theFexecution of the loop.  What happens if I > Limit?  If I = Limit?  How>does changing Add affect the number of executions of the loop?
Information───────────EThe WHILE loop is a general-purpose looping construct that puts the<test for the terminating condition at the top of the loop.Syntax:  WHILE <boolean-expression> DO    <statement>JAs long as <boolean-expression> evaluates True, <statement> is executed;?if <boolean-expression> evaluates as False on the first pass,F<statement> is never executed. This is in contrast to the REPEAT/UNTILGloop, which always executes the statement(s) in the loop at least once.DAs with the FOR loop, a begin/end block is necessary to execute more'than one statement inside a WHILE loop.   program WhileDemo;   uses Crt;   var     N : LongInt;   begin8     while not KeyPressed do    { a semi-infinite loop }*       Write('--Press any key to stop--');     Writeln; Writeln;,     Write('Enter a number (99 to quit): ');     Readln(N);     While N <> 99 do
     begin       Writeln('N * N =', N*N);.       Write('Enter a number (99 to quit): ');       Readln(N)	     end;   end. { WhileDemo }EThis example demonstrates the WHILE loop. The variable declarations \are as follows:var  I : integer;  Limit : integer;  Add : integer;;What's the main difference between a WHILE and REPEAT loop?.A WHILE loop will always execute at least once/A REPEAT loop will always execute at least once(A WHILE loop must have an index variable2A WHILE loop can be infinite; a REPEAT loop cannot;A REPEAT loop is checked for exit at the bottom of the loopwhile true do;Is an infinite loopWill execute once and then stopWill never executeIs not a legal Pascal statement?A WHILE loop's exit condition is checked at the top of the loop0Which of the following loops will never execute?while (2 > 3) or (5 < 10) dowhile true and false dowhile true or false dowhile (6 <= 6) and (5 >= 5) do,true and false = false; true or false = true+Which of the following is an infinite loop?while (2 > 3) or (5 < 4) do ;while true and false do ;while true or false do ; while (6 <= 5) and (5 >= 6) do ;,true and false = false; true or false = true
The Example───────────HTry different combinations of I, Limit, and Add to see the effect on theFexecution of the loop.  What happens if I > Limit?  If I = Limit?  How>does changing Add affect the number of executions of the loop?
Information───────────BThe REPEAT and UNTIL statements form a general-purpose loopingHconstruct with the test for the terminating condition at the bottom of	the loop.Syntax:     REPEAT       <statement(s)>     UNTIL <boolean-expression>CAs long as <boolean-expression> evaluates False, the statement(s)Fbetween REPEAT and UNTIL are executed. Note that the statements in theCloop are always executed at least once.  This is in contrast to theFWHILE and FOR loops, which, depending on the initial values, might not>execute even a single time. Also unlike FOR and WHILE loops, aDbegin/end block isn't required to execute more than one statement in	the loop.   program RepeatUntilDemo;   uses Crt;   var     N : LongInt;   begin     repeat(       Writeln('Press any Key to Stop');B     until KeyPressed;   { Returns True when a key is pressed... }     repeat.       Write('Enter a number (99 to quit): ');       Readln(N);       Writeln('N * N' =, N*N);     until N = 99;   end. { RepeatUntilDemo }NThis example demonstrates how a REPEAT loop works. The variable declarations \are as follows:var  I : integer;  Limit : integer;  Add : integer;#Which of the following is NOT true?(A REPEAT loop must execute at least once+A REPEAT loop doesn't need a begin/end pair)A REPEAT loop must have an index variableA REPEAT loop can be infinite("repeat ... until 20 > 10" executes oncerepeat ... until true;Is an infinite loopWill execute exactly onceWill never executeIs not a legal Pascal statement8A REPEAT loop is checked for exit at the end of the loop,Which of the following loops will never end? repeat ... until true and false;repeat ... until true or false;&repeat ... until (-2 < 6) and (3 > 2);)repeat ... until (-4 < -5) or (10 >= 10);true OR false = true
The Example───────────FSince type Day has only 7 possible values, the ordinal value of D1 andFD2 must be between 0 and 6 (inclusive) to be meaningful.  Keep this inAmind when converting X to D1 or D2.  What happens when you try toGincrement D1 or D2 when they equal Saturday?  What happens when you try-to decrement D1 or D2 when they equal Sunday?
Information───────────ETo create an enumerated type, the programmer lists ("enumerates") aEseries of identifiers representing the values a variable of that typecan have. For example:typeJ  days = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);,  precipitation = (rain, snow, sleet, none);3  color = (black, white, blue, green, red, yellow);FOnce an enumerated type is defined, one or more variables of that typecan be declared:   var     Today: days;     Weather: precipitation;     Paint: color;AAssigning to a variable of an enumerated type requires one of the@type's identifiers on the right side of the assignment operator.For example:     Today := Thursday;     Weather := rain;     Paint := green;BEnumerated types are inherently ordered; there's a lowest value, a@highest value, and a number of distinct values in between. It isFsometimes necessary to use the Ord function to turn a variable of anEenumerated type into the underlying integer value that represents it.CThe first value in the enumeration list has a value of 0, while theEhighest has an ordinal value equal to the total number of elements in>the type, minus 1. So for enumerated type days, Monday = 0 andSunday = 6.   program EnumeratedTypesDemo;   type<     chessPiece = (pawn, knight, bishop, rook, queen, king);   var     thePiece: chessPiece;   beginH     thePiece := Rook;      { no quotes around Rook; it isn't a string }     if thePiece > knight thenD       Writeln('The piece is either a bishop, rook, queen, or king')	     else9       Writeln('The piece is either a pawn or a knight');     Writeln(Ord(thePiece));      thePiece := Succ(thePiece);     Writeln(Ord(thePiece));   end. { EnumeratedTypesDemo }NThis example demonstrates how enumerated types work. The variable declarationsare as follows:type  Day = (Sunday, Monday,         Tuesday, Wednesday,         Thursday, Friday,         Saturday);var  D1, D2 : Day;1Objects of enumerated types can be added togetherTrueFalse Can you add Monday to Wednesday?1Given: type Days = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);Succ(Tue) = WedSucc(Pred(Tue)) = TueSucc(Wed) = Pred(Fri)All of the above$Succ = successor; Pred = predecessor1Given: type Days = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);Ord(Mon) = 0Ord(Mon) = 1Ord(Mon) = Mon'None of the above are legal expressions)Encodings for enumerated types begin at 0
The Example───────────JThe procedure ReadSet is not a built-in Turbo Pascal procedure.  It existsHonly for the purpose of this example, and allows you to read in a set ofKletters as a string.  When you use ReadSet to read in the members of a set,Ktype in a string of letters that correspond to the letters that you want toIbe in the set.  When a set is displayed as a variable, it is displayed inIstandard set notation, i.e., if more than two adjacent letters are in theKset, they will be displayed with a ".." between them.  For example, the setF[C, D, E] will be displayed as [C..E].  Also, the elements of each setL(since they are chars) are assumed to have single quotes around each letter,Dwhich are not displayed.  For example, the set [A, C..E, X] would be4technically correct if displayed as ['A'..'C', 'X'];
Information───────────HSets, a collection of objects of the same ordinal type, are an elegant/tool for expressing relationships in a program.DThe base type of the set (the type of objects contained within it)Emust have 256 or fewer possible values. Thus, you can define a set ofGtype char, or a set of the subrange 75..98.  But you can't define a set>of type integer, because it would have 65,536 possible values.GA set is created by enclosing within brackets a comma-delimited list ofDobjects of the same ordinal type. If the list contains elements with@consecutive ordinal values, you can use subrange notation (two>expressions separated by two periods). Here are some examples:4   []                                      empty setB   [1,3,5,7,9]                             set of integer subrange6   ['A'..'Z']                              set of char6   [Mon,Wed..Fri]                          set of Days8   [January..April, September..December]   set of MonthsDefining a Set TypeHTo define a set type, use the reserved words "set of", followed by the%name of the base type.  For instance:   typeF     CharSet = set of char;        { Set of objects of the type char }?     MonthDays = set of 1..31;     { set of integer subrange  }4     DayType = (Sun, Mon, Tue, Wed, Thur, Fri, Sat);@     Days = set of DayType;        { Set of objects of DayType }B     Colors = set of (Red, Green, Blue);   { Set of objects of theI                           anonymous enumerated type (Red, Green, Blue) }    var      wd : Days;	    begin      wd = [Mon..Fri];FSets can be processed with a number of special operators. Assuming thefollowing sets:    set1 := ['A', 'B', 'C'];    set2 := ['C', 'D', 'E'];    set3 := ['A', 'B', 'C'];    set4 := ['A', 'B'];>The union operator (+) adds two sets, producing a third set:0        set1 + set2 = ['A', 'B', 'C', 'D', 'E'];GThe membership operator (in) tells whether one set is fully containedwithin a second set:#        if ('A' in set1) then . . .FThe difference operator (-) subtracts one set from another, that is,Call members of the first set that aren't also members of the secondset.         set1 - set2 = ['A', 'B']DThe intersection operator (*) produces a set containing the valuescommon to both sets:        set1 * set2 = ['C']?Some of the operators used with numbers and strings can be used%on sets, but with different meanings.JThe equality operator (=) returns a Boolean value indicating whether twosets are exactly the same:         set1 = set3 returns TRUE!        set1 = set2 returns FALSEMThe inequality operator (<>) returns a Boolean value indicating whether twosets are different:"        set1 <> set3 returns FALSE!        set1 <> set2 returns TRUEGThe inclusion operators (<= and >=) return a Boolean value indicatingBwhether a set is a subset of another set.  The <= operator returnsHTRUE if the first set is a subset of the second set, and the >= operator<returns TRUE if the second set is a subset of the first set."        set1 <= set2 returns FALSE!        set4 <= set1 returns TRUE"        set3 >= set2 returns FALSE!        set1 >= set4 returns TRUE   program SetsDemo;   uses Crt;   var/     Alphabet, Vowels, Consonants: set of char;
     C: char;!   function LCase(C: char): char;1   { return lowercase equivalent of parameter C }   begin     if C in ['A'..'Z'] then        LCase := Chr(Ord(C) + 32)	     else       LCase := C;   end; { LCase }   begin { SetsDemo }     Alphabet := ['a'..'z'];)     Vowels := ['a', 'e', 'i', 'o', 'u'];%     Consonants := Alphabet - Vowels;     repeat        Write('Type a letter: ');       C := LCase(ReadKey);       if C in Vowels then-         Writeln('That character is a vowel')       else       if C in Consonants then1         Writeln('That character is a consonant')       else       if C in [' '..'~'] thenB         Writeln('That character is a printable ASCII character');      until C in [#3,  #27, #13];   end. { SetsDemo }KThis example demonstrates some of the operations that can be performed on \/sets. The variable declarations are as follows:type  Letters =    set of 'A'..'Z';var  S1, S2, S3 : Letters;  C : char;[1, 2, 3] + [4, 5, 6] =[]	[1, 2, 3]	[4, 5, 6][1, 2, 3, 4, 5, 6]+ is the set union operator[1, 2, 3] * [4, 5, 6] =[]	[1, 2, 3]	[4, 5, 6][1, 2, 3, 4, 5, 6]"* is the set intersection operatorSetVar := ['AA'..'ZZ'];contains 26 elementscontains more than 26 elementscontains 0 elementsIs not a legal Pascal statementStrings are not ordinal types[1..3, 5..8] - [1..2, 6..9] =[1..2, 6..9][1..3, 5..8][3, 5][2, 9]-The - operator subtracts one set from another/Which of the following is NOT a valid set type:set of charset of byteset of real4set of days   { where days = (Mon, Tue, Wed ... )  })An element of a set must be a simple type#Write(['A'..'C'] = []) will output:ABCTrueFalseIs not a legal Pascal statement(The = operator produces a Boolean resultWrite(['A'..'C']) will output:ABC'A'..'C'
'A', 'B', 'C'Is not a legal Pascal statement>Write can only output ordinal values and strings to the screen4How many bytes are used to represent a set variable?132256#Depends on the base type of the set6One bit is reserved for each possible element of a set
The Example───────────FExperiment with the different functions and procedures, paying carefulHattention to what happens if the parameters of the procedure or functionJare out of bounds or illegal (examples: Delete(S1, 3, 5) where S = 'abcd',CVal(S1, X1, X2) where S1 = 'X', Val(S2, X2, X1) where S2 = '123Z').
Information───────────FA string is a one-dimensional array of ASCII characters, that is, anDarray of type char. Using various built-in procedures and functions,Cyou can manipulate strings in the following ways: add characters to@them, delete characters from them, and combine and compare them.DTo specify a string type, after the reserved word string, tell theFcompiler the maximum number of characters a variable of that type willcontain. For example:   type     bigstring = string[80];   var     S: bigstring;EThis declares S as a string variable that can consist of (at most) 80@characters. If you attempt to assign more than n characters to a;variable of type string[n], the excess characters are lost.CThe following functions and procedures manipulate string variables:Dfunction Concat(S1, S2 {, S3,...,Sn}) returns a string composed of<<S1> through <Sn> joined together ("concatenated"); the plus0sign can also be used to perform this operation.Dfunction Copy(S, Position, Len) returns a string composed of <Len>>characters in string <S> starting with character # <Position>.Bprocedure Delete(S, Position, Num) deletes <Num> characters from0string <S> starting with character # <Position>.Gprocedure Insert(Source, Destination, Position) inserts <Source> into1<Destination> starting at character # <Position>.8function Length(S) returns current length of string S.Hfunction Pos(Pattern, Target) returns the position of <Pattern> within	<Target>.Comparing Strings?Strings are compared based on their underlying ASCII values andDlength, in that order. For example, "cat" is less than "dog" because?the ASCII value of 'c' is less than the ASCII value of 'd'. TwoFstrings are equal only if they contain exactly the same characters. IfFtwo strings have different lengths, but are identical up to the lengthBof the shorter string, then the shorter string is considered to be?less than the longer string. This means that "cat" is less than"cats".FCase is significant when comparing strings. "Cat" is less than "cat"Fbecause uppercase letters have lower ASCII values than their lowercaseequivalents.   program StringTest;   type      MaxString = string;   var     InString: MaxString;(   procedure ToLower (var S: MaxString);=   { convert uppercase letters in S to lowercase equivalent }   var     Index : integer;   begin#     for Index := 1 to Length(S) do%       if S[Index] in ['A'..'Z'] then-         S[Index] := Chr(Ord(S[Index]) + 32);   end; { ToLower }%   procedure CountLetters(S: string);   var
     C: char;     I: integer;.     LetterCount : array['a'..'z'] of integer;   begin     for C := 'a' to 'z' do       LetterCount[C] := 0;     for I := 1 to length(S) do1      lettercount[s[I]] := lettercount[s[I]] + 1;'     Writeln('This string contains: ');     for C := 'a' to 'z' do
     begin+       Write(LetterCount[c]:3,' ',c,'   ');E       if (ord(C) mod 6) = 0 then Writeln;   { six letters per line }	     end;
     Writeln;   end; { CountLetters }   var     I : integer;   begin { StringTest }     repeat!       Write('Enter a string: ');       Readln(inString);       ToLower(inString);       CountLetters(inString);       Write('Backwards: ');,       for I := Length(inString) downto 1 do         Write(InString[I]);       Writeln;     until InString = 'quit';   end. { StringTest }KThis example demonstrates some of the operations that can be performed on \2strings. The variable declarations are as follows:var  X1, X2 : integer;  S1, S2 : String[10];5StringVar := CharVar; is a legal assignment statementTrueFalseStrings of length 1 are allowed.Given StringVar = 'ABCD':  Length(StringVar) =04'ABCD' Is not a legal Pascal expressionOrd(StringVar[0]) = 4BGiven StringVar = 'ABCD': Delete(StringVar, 1, Length(StringVar));StringVar = ''StringVar = 'A'StringVar = 'ABCD'Is not a legal Pascal statement>Definition:  Delete(StringVar, FirstCharToDel, NumCharsToDel);Copy('ABCDEFGHIJ', 4, 3) ='CDEF''ABCD''DEF''HIJ'CDefinition: Copy(StringExpression, FirstCharToCopy, NumCharsToCopy)Pos('DE', 'ABCDEFGH') =3456 Definition: Pos(Pattern, Target)
The Example───────────GTry different values of X and Y, and see if you can guess ahead of timeKwhich character on the screen will change when you execute "A[X, Y] := C;".
Information───────────FAn array is a list of variables of the same type. Individual members?of the list are referred to by specifying the list's name and a+position (or index) within it. For example,   var#     Check : array [1..10] of real;<tells the compiler that variable Check is a list of ten realEvariables. Each element of an array is referred to by the name of theCarray, followed by its index (position) enclosed in brackets. Thus,=array Check contains 10 unique variables: Check[1], Check[2],ECheck[3], Check[4], Check[5], Check[6], Check[7], Check[8], Check[9],Dand Check[10]. You can use any of these variables wherever you would@use a regular real variable. Furthermore--and this is what makesCarrays useful--the index value can be any expression that yields anEinteger in the range 1..10. For example, if variable J is of the typeinteger, this for loop   for J := 1 to 10 do     Check[J] := 0.0;zeros each variable.JArrays can be multidimensional; that is, arrays of arrays (of arrays...)can be created:   var=     YearlyHighs = array [1..12] of array [1..31] of integer;which is the same as2    YearlyHighs = array [1..12][1..31] of integer;and, in shorthand form:2    YearlyHighs = array [1..12, 1..31] of integer;0Such an array must be indexed with two integers:F   Writeln('The hottest it ever got on July 4 is ', YearlyHighs[7,4]);   program ArrayDemo;   uses Crt;   const     maxrolls = 50000;   var&     Counts: array [2..12] of LongInt;     RollCount : longint;     N: integer;     ThisRoll: integer;     MostPopularRoll: integer;      HighestTotalSoFar: longint;
     C: char;,   function RollEm: integer;  { Rolls dice }   begin)     RollEm := Random(6) + Random(6) + 2;   end; { RollEm }   begin { ArrayDemo }     Randomize;     RollCount := 0;     for N := 2 to 12 do4       Counts[n] := 0;      { initialize the array }     while not KeyPressed do
     begin"       RollCount := RollCount + 1;       ThisRoll := RollEm;0       Counts[ThisRoll] := Counts[ThisRoll] + 1;	     end;-     C := ReadKey;   { absorb the keystroke }-     Writeln('After: ', RollCount, ' Rolls');     Writeln(' #     Count ');     for N := 2 to 12 do(       Writeln(n:2, '   ', Counts[n]:7);/     { Now search for the most popular number }     HighestTotalSoFar := 0;     for N := 2 to 12 do,       if Counts[N] > HighestTotalSoFar then       begin(         HighestTotalSoFar := Counts[N];         MostPopularRoll := N       end;<      Writeln('The most popular roll is ', MostPopularRoll);   end. { ArrayDemo }HThis shows how a two-dimensional array works. The variable declarations\are as follows:type  AnArray =    array[1..9, 1..9]          of char;var  X, Y : byte;  C : char;  A : AnArray;0An array can be composed of elements of any typeTrueFalse"array[1..10] of file" is legal&How many dimensions can an array have?234Limited only by memory7"array [1..2, 1..2, 1..2, 1..2, 1..2] of byte" is legal0What is the maximum size (in bytes) of an array?	Unlimited64K32K?No type can be declared such that a variable of that type > 64K@Given: a : array[1..10] of char;    The statement:  a[0] := 'C';Is a legal Pascal statementWill cause a compiler errorWill cause a runtime error7Will cause a runtime error only if range-checking is on<{$R+} turns on range-checking for ordinals and array indexesBIf Players is an enumerated type, which type declaration is legal?!type a = array[1..10] of Players;,type b = array[Players, Players] of integer;#type c = array[Players] of Players;All of the above+Enumerated types can serve as array indexes6An array be assigned to another array of the same typeTrueFalseIFile types excepted, variables of the same type are assignment compatible7How many bytes are used to represent an array variable?102030 Depends on the type of the array-An array [1..10] of integer requires 20 bytesDWhat ordinal type cannot be used as an index in an array definition?integercharrealuser-defined ordinal&an array index must be an ordinal typeWrite(ArrayVar);Is a legal procedure callIs NOT a legal procedure call-Write can output ordinals, reals, and strings)The safest way to initialize an array is:With a FOR loopWith a FILLCHAR statement(FillChar performs no checking whatsoever
The Example───────────JTry entering completely different values for the fields of the two recordsLX and Y, and see how executing "X := Y" or "Y := X" will change both fields.
Information───────────GRecords are a structured type consisting of collections of objects of=other types. A record variable can be used as a whole, or itsAindividual components, called fields, can be used individually.2The syntax for a record declaration is shown here:     RecType = record       <field1>: <sometype>;       <field2>: <sometype>;       .       .       .       <fieldn>: <someType>;	     end;BOnce a variable of a record type has been declared, you can assignGinformation to one of its fields by writing the name of the variable, aLperiod, and then the field name. In general, a field of a record can be usedIwherever a variable of the field's type would be acceptable. For example:   type     student = record       name: string[40];       age: integer;       GPA: real;3       major: ( music, english, history, science );	     end;   var     S : student;   begin     S.name = "Susan Carlson";     S.age = 19;     S.GPA = 3.41;     S.major = english;   end.EThe WITH statement is a shorthand notation for accessing the fieldsCof a record; inside a WITH statement (which may include a begin/endCblock), the name of the record is unnecessary to access its fields.@For example, the previous assignments to record variable S couldhave been written as:   begin     with S do
     begin       name = 'Susan Carlson';       age = 19;       GPA = 3.41;       major = english;	     end;   end.Variant RecordsFA variant record is a special form of record in which some or all ofBthe fields are given overlapping storage in memory. This allows anAapplication to conserve memory when many of a record's fields are<inappropriate for a particular class of object being stored.CFor example, a record that represents a transaction in a departmentCstore can have separate fields according to the method of purchase;-one for checks, and another for credit cards.type(  paymentType = ( cash, check, credit );  purchase = record               Amount : real;                Date : string[8];.               case payMethod : paymentType of                 cash  : ( );F                 check : (checkNo : integer; licenseNumber: longint );C                 credit: (cardNo : longint; expiration: string[8]);             end;?The variant part of the record definition must come at the end.   program RecordExample;   type     check = record       number: integer;       amount: real;2       date: array [1..8] of char;  { '99/99/99' }       payee: string[40];	     end;   var     MyCheck : check;     YourCheck: check;   begin4     MyCheck.number := 753;    { Christmas present }#     MyCheck.amount := 87000000.00;      MyCheck.date := '12/25/88';     MyCheck.payee := 'Myself';B     YourCheck := MyCheck;   { all fields assigned automatically }.     YourCheck.number := YourCheck.number + 1;     with YourCheck do
     begin#       Writeln('Amount = ',amount);       Writeln('Date = ',date);	     end;   end. { RecordExample }KThis example demonstrates some of the operations that can be performed on \2records. The variable declarations are as follows:type  RecType = record    Name : String[10];    Age : byte;  end;var  X, Y : RecType;5The fields of a record type can be other record typesTrueFalse6Statements like bigRec.smallerRec.i := 14 are possibleThe WITH statement:makes for terser source code(can result in more efficient object code"wastes memory but speeds executionA and B-Sorry, no hint is available for this question;Variant records simplify program structure, but waste spaceTrueFalseDIn variant records, mutually exclusive fields share the same storage
The Example───────────IStep through the source code to see how procedures and functions execute.BNote how the return value of the function F is assigned to Y after
exiting F.
Information───────────EProcedures and functions are named modules of code. Their primaryFpurpose is to subdivide large, complex programming tasks into smaller,Gsimpler ones. Both procedures and functions have a structure similar toCthat of a program, and can declare constants, types, variables, andDnested procedures and functions, just like a program, as shown here:   procedure <ProcName>;   <constant-definitions>   <type-definitions>   <variable-definitions>!   <nested-procedure-definitions>   begin     <statements>   end;DA function is like a procedure except it always returns a value of@some type; typically, a function's return value is the result of?calculations based on values passed to the function at runtime. Calling Procedures and FunctionsDA procedure is called explicitly with a statement that consists onlyEof the procedure's name; a function is called implicitly by using its=name in an expression within a statement (often an assignmentstatement). For example:   program ProcsAndFuncts;   var     N : integer;   procedure SayHello;   begin     Writeln ('Hello!');   end; { SayHello }   function Seventeen: integer;   begin     Seventeen := 17;   end; { Seventeen }   begin { ProcsAndFuncts }6     SayHello;          { calling procedure SayHello }6     N := Seventeen;    { calling function Seventeen }   end. { ProcsAndFuncts }&Returning from a Procedure or FunctionCA procedure or function returns program flow to the calling routineEwhen the last statement in the routine is executed or, alternatively,)when the EXIT statement is encountered.Local VariablesHAny variables declared in a procedure or function are said to be localDto that routine. Because of the way these variables are allocated onBthe stack when the routine is called and then deallocated when theFroutine returns, local variables have a lifetime equal to the durationBof the call. In addition, as with global variables, the value of aFlocal variable is undefined upon entry to a procedure or function. Forexample:    program VariableLifetimeDemo;   procedure TestProc;   var     N : integer;   begin     Writeln( N );
     N := 66;   end; { TestProc }!   begin { VariableLifetimeDemo }     TestProc;     TestProc;     TestProc;    end. { VariableLifetimeDemo }EThe output produced by this program is unpredictable, as each call of?TestProc may result in any integer value being printed out. The&assignment of 66 to N doesn't "stick."Parameter PassingCAn important concept in procedure and function usage is parameterFpassing, the process by which information is sent to (and optionallyJreturned from) a program's procedures and functions. See the Tutor example-named Parameter Passing for more information.	Recursion@A procedure or function can legally call itself; this process isAcalled recursion, and allows the creation of subtle and compact:algorithms. See the Tutor example named Recursion for moreinformation.JThis example demonstrates how procedures and functions work. The variable\declarations are as follows:var  X, Y : integer;Procedures and functionsAre program subdividersAlways return values!Must be called within expressionsAll of the aboveEProcedures are called as separate statements and don't return a value3Like a Pascal program, procedures and functions canDeclare variablesDeclare constants and types'Declare nested procedures and functionsAll of the above'Pascal programs have a nested structure)Program flow returns from a function when!The EXIT statement is encountered(A value is assigned to the function name.The function runs out of statements to executeA and C*Assigning to the function name is optional
The Example───────────FStep through the code to see the difference between variable and valueHparameters.  Note that A and B are only defined when inside procedure P,Kand do not get initialized until the "begin" statement of procedure P.  SeeKthat when A is changed, the value of A changes, but when B is changed, both1B and Y change (since B is a variable parameter).
Information───────────=Procedures and functions can declare two types of parameters:Freference parameters (those preceded by the VAR reserved word) and'value parameters (those without VAR).:When a value parameter is passed at runtime, a copy of the?parameter--not the parameter itself--is placed on the stack. InAeffect, this copy becomes a local variable of the called routine.EAs a local copy, the procedure can assign to it without affecting the)original variable in the calling routine.<In contrast, when a reference (VAR) parameter is passed to aDprocedure, the address of the parameter is placed on the stack. This?means that assigning to the variable in the called procedure orEfunction affects the caller's variable. Only variables (not constantsCor expressions) can be passed as reference parameters--because only#variables have addresses in memory.DStack size constraints can make it advantageous to pass variables byBreference, even when you don't intend to change a parameter in theFcalled routine. For example, it takes 10K of stack space to pass a 10K9array by value, but only 4 bytes to pass it by reference.BYou can determine the amount of memory allocated to the stack withITurbo Pascal's Options/Compiler/Memory sizes option; by default the stackis set to 16K.   program ParameterDemo1;   type!     t = array [1..5000] of char;   procedure ByValueProc(a: t);   begin     a[2500] := 'F';   end; { ByValueProc }'   procedure ByReferenceProc(VAR a: t);   begin     a[2500] := 'F';   end; { ByReferenceProc }   var     AnArray: t;   begin { ParameterDemo1 }     ByValueProc(AnArray);     Writeln(AnArray[2500]);     ByReferenceProc(AnArray);     Writeln(AnArray[2500]);   end. { ParameterDemo1 }   program ParameterDemo2;   var     A : integer;    procedure Proc1(N : integer);   begin
     N := 55;   end; { Proc1 }$   procedure Proc2(var N : integer);   begin
     N := 33;   end; { Proc2 }   var     G : integer;   begin { ParameterDemo2 }
     G := 22;     Proc1(G);     Writeln(G);     Proc2(G);     Writeln(G);E   { Proc2(55);     This line won't compile, because you can't pass }1   {                constants as var parameters }   end. { ParameterDemo2 }DThis example demonstrates the difference between value and variable\5parameters. The variable declarations are as follows:var  X, Y : integer;)Given: procedure MyProc (var A: integer);A is a reference parameterA is a value parameter+MyProc cannot affect the caller's copy of AA and C4Reference parameters are preceded by the VAR keyword:Given: procedure MyProc (var A: maxstr); (maxstr = STRING),Calling MyProc places 255 bytes on the stack,Calling MyProc places 256 bytes on the stack*Calling MyProc places 4 bytes on the stack*A reference parameter is passed by address<Given: procedure MyProc (A: maxstr); (where maxstr = STRING).Calling MyProc will put 256 bytes on the stack.Calling MyProc will put 100 bytes on the stack,Calling MyProc will put 4 bytes on the stack*A reference parameter is passed by address>Given: procedure MyProc(var A: integer);  which call is legal?%MyProc(A*B);   (A and B are integers)MyProc(14);
MyProc(A);All of the above4Only variables can be passed as reference parameters
The Example───────────GOpen a new text file (with Assign and Rewrite) and write some values toGit.  Close the file, and then Reset it.  Read the values back in.  LookAat the difference between Read and Readln, and Write and Writeln.
Information───────────DText files are disk files consisting of lines of ASCII characters.EUnlike memory-based Pascal data structures, text files are relativelyEpermanent. Also, text files have no predefined length; they can be asHlong as your disk space permits. Text files are represented by variables%of predefined type text. For example:    var      MyFile : text;EOnce a little setup work has been performed, you can read a text file@as easily as reading the keyboard, and write to it as though youBwere writing to the screen. The same Writeln/Readln procedures areCused, with the the name of the file preceding the data to output inthe call. For example:   Write('Hello');!sends 'Hello' to the screen, and:   Write(MyFile, 'Hello');-sends 'Hello' to the end of text file MyFile.FThe Assign procedure makes a connection between a Pascal variable ofGtype Text and the MS-DOS file name you want the file to have. Use theIReset procedure to prepare to read a text file; use Rewrite to createEa new, empty text file in preparation for writing to it. Call Close(when you're through working with a file.CText files are sequential; that is, they must be accessed in order.AThis is in contrast to typed (random-access) files in which any.part of the file can be accessed in any order.   program MakeATextFile;   var     TheFile: Text;   begin#     Assign(TheFile,'BORLAND.TXT');5     Rewrite(TheFile); { create a new, empty file and1                         prepare to write to it }.     Writeln(TheFile,'Borland International');1     Writeln(TheFile,'4585 Scotts Valley Drive');1     Writeln(TheFile,'Scotts Valley, CA  95066');     Close(TheFile);   end. { MakeATextFile }   program ReadATextFile;   var     TheFile: Text;     S: String;   begin#     Assign(TheFile,'BORLAND.TXT');C     Reset(TheFile);           { prepare to read an existing file }     while not EOF(TheFile) do
     begin5       Readln(TheFile,S);      { read from the file }:       Writeln(S);             { and write to the screen }	     end;     Close(TheFile);   end. { ReadATextFile }KThis example demonstrates some of the operations that can be performed on \5text files. The variable declarations are as follows:var  F : Text;  C : char;  I : integer;  R : real;
  S : String;#A text file is a random-access fileTrueFalse<The records in a random-access file all have the same length0What's the difference between Write and Writeln? Write can only take one argument8Writeln automatically outputs a carriage return/linefeed4Writeln waits for the user to type a carriage return3Write doesn't advance to the start of the next lineCWhich data type CANNOT be sent to a text file in a Write statement?realstringcharsetGOnly ordinal, real, and string types can be sent to text files by Write5The fastest way to move to the end of a text file is:Append(FileVar);!Seek(FileVar, FileSize(FileVar));3while not EOF(FileVar) do Read(FileVar, StringVar);>while not EOF(FileVar) do Seek(FileVar, FilePos(FileVar) + 1);DFileSize returns the number of records; FilePos the current record #;The fastest way to remove the first line of a text file is:Delete(FileVar, 1);5Copy the first line to a new file, erase the new file6Copy the other lines to a new file, erase the old file7There is no way to remove the first line of a text fileADelete(StringVar, 1, 1) removes the first character from a string0Which of the following is true about text files?:After you Assign the file name, you can read from the file<If you open a text file with a Rewrite, you can read from it.Readln and Writeln can be used with text filesText files are files of recordsAa text file cannot be open for reading and writing simultaneously7Which of the following CANNOT be used with a text file?EOFEOLNSeekResetHSeek moves the file pointer to a specific record in a random access fileBThe statement: while not EOF(FileVar) do Read(FileVar, StringVar);Reads every line in a text file#Reads the first line of a text fileCauses a compiler errorCauses a runtime error<Read(StringVar) reads up until the next carriage return (CR):while not EOF(FileVar) do Readln(FileVar, StringVar) WILL:Read every line in a text file"Read the first line of a text fileCause a compiler errorCause a runtime errorFReadln reads until the next character is a CR, then it skips past EOLN
/ TYPED FILESWith a FOR loopWith a FILLCHAR statement(FillChar performs no checking whatsoever
The Example───────────IOpen a new typed file (with Assign and Rewrite) and write some records toGit.  Close the file, and then Reset it.  Read the values back in.  LookAat how using Seek can retrieve records from any part of the file.
Information───────────CTyped files are disk files that consist of a numbered sequence ofFobjects of some type. Because the length of each object in the file isFconstant, Turbo Pascal can calculate the position of a given object in2the file and read or write that position directly.FTyped files are therefore more efficient than text files in situations'that must read and write data randomly.   program CreateTypedFile;3   { create a file consisting of 100 real numbers }   var     TheFile: file of real;
     R: real;     N: integer;   begin!     Assign(TheFile,'REALS.DTA');5     Rewrite(TheFile); { create a new, empty file and1                         prepare to write to it }     for N := 1 to 100 do
     begin       R := sqrt(N);4       Write(TheFile, R);  { write out a real in the5                             internal binary format }	     end;     Close(TheFile);   end. { CreateTypedFile }   program UseTypedFile;H   { read a value between 1 and 100 and pull the appropriate square root4     from the file created in the previous program }   var     TheFile: file of real;
     R: real;     N: integer;   begin!     Assign(TheFile,'REALS.DTA');     Reset(TheFile);$     Write('Enter value (1-100): ');     Readln(N);     while N > 0 do
     begin9       Seek(TheFile,N-1);          { record 0 = sqrt(1) }       Read(TheFile,R);3       Writeln('The square root of ', N, ' is ',R);&       Write('Enter value (1-100): ');       Readln(N);	     end;   end. { UseTypedFile }MThis example shows some of the operations for typed files. The declarations \are:type  RecType = record    I : integer;    S : String[10];
    R : real;  end;var  F : File of RecType;  P : word;>Which of the following CANNOT be used on a random-access file?SeekAppendWriteRead#BlockWrite is used on untyped files>The fastest way to move to the end of a random-access file is:Append(FileVar);!Seek(FileVar, FileSize(FileVar));3while not EOF(FileVar) do Read(FileVar, RecordVar);>while not EOF(FileVar) do Seek(FileVar, FilePos(FileVar) + 1);DFileSize returns the number of records, FilePos the current record #7The fastest way to remove the last record of a file is:'Delete(FileVar, FileSize(FileVar) - 1);6Seek(FileVar, FileSize(FileVar) - 1); Delete(FileVar);8Seek(FileVar, FileSize(FileVar) - 1); Truncate(FileVar);3There is no way to remove the last record of a fileADelete(StringVar, 1, 1) removes the first character from a string8The fastest way to remove the first record of a file is:Delete(FileVar, 1);7Copy the first record to a new file, erase the new file8Copy the other records to a new file, erase the old file4There is no way to remove the first record of a file3Delete(StringVar, 1, 1) works on strings, not files
The Example───────────LLook at what effect toggling the different elements of the color byte has onCthe color.  See how the bits of the color byte determine the color.
Information───────────KOn PCs with color video capability (including CGA, EGA, and VGA boards) andKa color monitor, Turbo Pascal's TextColor and TextBackground proceduresGallow you to control the color of text, both foreground and background,+output by the Write and Writeln procedures.'   procedure TextColor(Color: integer);,   procedure TextBackground(Color: integer);EFor TextColor, use a value for <Color> between 0 and 15, according tothis table:'   Black     = 0;     DarkGray     = 8;'   Blue      = 1;     LightBlue    = 9;(   Green     = 2;     LightGreen   = 10;(   Cyan      = 3;     LightCyan    = 11;(   Red       = 4;     LightRed     = 12;(   Magenta   = 5;     LightMagenta = 13;(   Brown     = 6;     Yellow       = 14;(   LightGray = 7;     White        = 15;2For TextBackground, <Color> can range from 0 to 7:   Black     = 0;   Blue      = 1;   Green     = 2;   Cyan      = 3;   Red       = 4;   Magenta   = 5;   Brown     = 6;   LightGray = 7;<These routines and color constants are declared in unit Crt.FEach byte of color on the display is made up of three components:  TheJforeground color, the background color, and the blink bit.  They arearranged as follows:GBit    7        6        5        4        3        2        1        0GValue 128       64       32       16       8        4        2        1L   ┌────────┬────────┬────────┬────────┬────────┬────────┬────────┬────────┐L   │        │        │        │        │   FG   │        │        │        │L   │ Blink  │ Red BG │Green BG│Blue BG │Intnsity│ Red FG │Green FG│Blue FG │L   │        │        │        │        │        │        │        │        │L   └────────┴────────┴────────┴────────┴────────┴────────┴────────┴────────┘GThis example shows how colors work on the IBM PC. The information below9shows how text prints if Color is the current text color.HHow many foreground colors are there in text mode on a graphics adapter?321684*4 bits are allocated for foreground colorsHHow many background colors are there in text mode on a graphics adapter?321684*3 bits are allocated for background colors?Which foreground and background colors produce "reverse video"?white on blackwhite on light grayblack on light graylight gray on white(Light gray is color 7, white is color 15
The Example───────────HTry each sound effect and see the variety of sounds that can be producedHusing just a handful of procedures.  If you press a key to stop a sound,Dthere may be a delay in processing the key while the sound finishes.
Information───────────;Unit Crt contains the following routines for creating tonesand sound effects:    procedure Delay(MS: integer);    procedure Sound(Hz: integer);   procedure NoSound;HSound starts a tone of frequency <Hz> playing; it lasts until you makeHthe NoSound call. The Delay routine is a general-purpose time waster9that doesn't return until <MS> milliseconds have gone by.KThis example shows some sample sound effects that have been created using \Hthe Sound, NoSound, Delay, and Random procedures.  The source code for \Dthese sound effects is also in the file SOUNDEX.PAS if you want to \
print it out.CWhat's the maximum length of a tone created by the Sound procedure?256 milliseconds
16 seconds1 minuteThere is no maximum length0A sound is turned off with the NoSound procedure&How many sounds can be active at once?4321ACalling Sound while another sound is active stops the first soundGIf NoSound is never called, will the sound stop when the program stops?YesNo<Once a sound starts, it can only be turned off with NoSound.
The Example───────────KExperiment with different-sized windows and see how they work when you typeItext into them.  Note that in your own programs you will have to save theEarea under the window in memory (as this example does) if you want toErestore the screen after getting rid of the window.  This is how most$programs with "pop-up" windows work.
Information───────────LUnit Crt's Window call enables you to create a window on the text display.)  procedure Window(X1,Y1,X2,Y2: integer);EAfter a call to Window, text output by Write and Writeln stays withinLthe borders of the new window; similarly, the ClrScr, ClrEOL, InsLine,?and GotoXY procedures act within the boundary of this window.   program WindowDemo;   uses Crt;   begin     Window(10,5,40,15);     ClrScr;     while not KeyPressed do?       Write('All output takes place in the new window . . .');   end. { WindowDemo }NThis example shows how the Window procedure works. The variable declarations \are as follows:var  X1, Y1, X2, Y2 : byte;The minimum window size is2 lines and 2 columns1 line and 1 column419 lines and 1776 columnsThere is no minimum(Window(78, 25, 80, 25) is a valid window+Which of the following is NOT a valid call?Window( 1,  1, 80, 25);Window(10, 30, 12, 35);Window(15, 20, 40, 23);Window( 5, 18, 80, 25);%The screen has 80 columns and 25 rows)What is the default (full-screen) window?Window(1, 1, 80, 25);Window(1, 1, 25, 80);Window(1, 25, 1, 80);Window(1, 80, 1, 25);"The lower-right corner is (80, 25)
The Example───────────LTry the different sorts and step through each algorithm, paying attention toLthe comparison order and whether a swap is made. You can see the best, worstJand random cases for each sort by using the lower three menu selections to+change the initial ordering of the numbers.
Information───────────EBy definition, sort routines place unordered numeric or string dataBinto ascending or descending order. Many sort algorithms have been?discovered, and delineating their characteristics is a favoritepastime of Pascal tutorials.
Bubble SortKThe bubble sort algorithm derives its name from the way it systematicallyJfloats the largest values in an array to the top, like bubbles in a bottleof soda.BThe algorithm goes like this: starting at the bottom of the array,Hcompare each adjacent pair of values; if the lower member of the pair isKgreater than the upper member, swap. Once you've worked your way to the topJin this fashion, theArray[ARRAYSSIZE] is known to be the largest number inJthe array. Now repeat the process, but this time stop one element short ofFthe top (since we already know this value is the largest). Repeat thisFprocess until finally on the last pass you examine only the bottom twomembers of the array.2   procedure BubbleSort (var theArray: arrayType);   var     last, current : integer;   begin&     for last := ARRAYSIZE downto 2 do$       for current := 1 to last-1 do8         if theArray[current] > theArray[current+1] then8           Swap(theArray[current], theArray[current+1]);   end; { BubbleSort }Insertion SortEThe insertion sort is on the simple end of the scale, and resembles>the way people sort a bridge hand. Working from one end of theIarray to the other, each value is placed in its correct position relative,to the values that have already been sorted.GThe routines shown here are designed to process arrays of integers into9ascending order (i.e., theArray[1] gets the lowest value;ItheArray[ARRAYSIZE] gets the highest), although with only trivial changesJthe algorithms could easily work with string data and/or descending order.   const     ARRAYSIZE = 100;   type0     arrayType = array[1..ARRAYSIZE] of integer;6   procedure InsertionSort (var theArray: arrayType );   var+     newValue, newPos, currentPos: integer;   begin$     for newPos := 2 to ARRAYSIZE do
     begin$       newValue := theArray[newPos];       currentPos := newPos;H       while (currentPos > 1) and (theArray[currentPos-1] > newValue) do       begin8         theArray[currentPos] := theArray[currentPos-1];&         currentPos := currentPos - 1;       end;(       theArray[currentPos] := newValue;	     end;   end; { InsertionSort }Shell SortNThe Shell Sort was invented by a computer scientist named Donald Shell.  HisIsorting method compares and swaps numbers the greatest distance from eachKother first, shrinking the distance between numbers until you return to the(ones in closest proximity to each other.=   procedure ShellSort(var List: ListType; ListMax: integer);   label     ExitLoop;   var(     Indx, Jndx, TheVal, Incr : integer;   begin     Incr := 1;     repeat       Incr := 3 * Incr + 1;     until Incr > ListMax;     repeat       Incr := Incr div 3;)       for Indx := Incr + 1 to ListMax do       begin         TheVal := List[Indx];         Jndx := Indx;,         while List[Jndx - Incr] > TheVal do         begin+           List[Jndx] := List[Jndx - Incr];           Jndx := Jndx - Incr;           if Jndx <= Incr then             goto ExitLoop;
         end;   ExitLoop:         List[Jndx] := TheVal;       end;     until Incr = 1;   end; { ShellSort }QuicksortGKing of the sorting algorithms is Quicksort. The gist of Quicksort issummarized here:0-- Pick a pivot point in the center of the array-- Partition the array:<   Exchange equal or larger elements (working from the left);   with equal or smaller elements (working from the right).9   Repeat this process until the array has been organized;   such that every value left of the pivot point is smaller;   than every value right of the pivot point, and the value4   at the pivot point itself is in exactly the right   position.<-- If there's more than one element left of the pivot point,@   call Quicksort recursively on the left-hand part of the array=-- If there's more than one element right of the pivot point,A   call Quicksort recursively on the right-hand part of the array/   procedure Quicksort(start, finish: integer);%   { sorts global variable theArray }   var"     pivot, left, right : integer;   begin     { set pivot point }     left := start;     right := finish;/     pivot := theArray[(start + finish) div 2];     { partition }     repeat&       while theArray[left] < pivot do         left := left + 1;'       while pivot < theArray[right] do         right := right - 1;       if left <= right then       begin1         Swap( theArray[left], theArray[right] );         left := left + 1;         right := right - 1;       end;     until right <= left;#     { sort right and left halves }3     if start < right then QuickSort(start, right);3     if left < finish then QuickSort(left, finish);   end; { QuickSort }5This example demonstrates various sorting algorithms.AOf the four types of sorts in this example, which is the fastest?Bubble SortInsertion Sort
Shell Sort	QuicksortIt's NOT Bubble SortKHow many comparisons will Bubble Sort make in sorting a 1000 element array?roughly 1,000 comparisonsroughly 10,000 comparisonsroughly 500,000 comparisons)depends on the initial state of the arrayABubble Sort makes (n*n - n) / 2 comparisons on an n-element arrayHFor a 10,000 number list, Quicksort is how much faster than Bubble Sort?slightly	two times	ten timesmore than 100 timesCBubble Sort is slow for small arrays and very slow for large arrays
The Example───────────IThe example shows how the stack in your Turbo Pascal programs is handled,Hand how variables are pushed onto and popped off of the stack.  See whatFhappens when you try to pop variables when StkPtr is at the top of theHstack, or when you try to push variables when StkPtr is at the bottom of
the stack.
Information───────────HA stack is a simple (and surprisingly useful) scheme for storing data.CAll data added to a stack must be added to the "top." Likewise, allDdata removed from a stack must be removed from the "top." This meansFthat any data item removed will always be the one most recently added.GBecause of this, stacks are sometimes known as "last in, first out" (orJLIFO) lists. When you add to a stack, you're said to be "pushing" dataGonto it; when you remove data, you're said to be "popping" the stack.   program StackDemo;   uses Crt;   const     MAXSTACK = 80;   var.     stackarray : array [1..MAXSTACK] of char;     stackPointer: integer;   procedure Push(C : char);   begin%    stackPointer := stackPointer + 1;"    stackArray[stackPointer] := C;   end; { Push }   function Pop : char;   begin     if stackPointer = 0 then       Pop := Chr(0)	     else
     begin(       stackPointer := stackPointer - 1;'       Pop := stackArray[stackPointer];	     end;   end; { Pop }   var     C : char;   begin { StackDemo }     stackPointer := 0;     Write('Enter a string: ');     repeat       c := ReadKey;       Write(c);       Push(c);     until c=#13;
     Writeln;     Write('Reversed: ');     repeat       c := pop;       Write(c);     until c = Chr(0);   end. { StackDemo }NThis example demonstrates how a simple stack works.  The variable declarationsare as follows:var  C : char;  B : byte;  I : integer;  W : word;  R : real;
  S : String;  StkPtr : word;Stacks are often called
LIFO lists
FIFO lists8FIFO = "First in, first out;" LIFO = "Last in, last out",Turbo Pascal programs use the stack to storeLocal variablesValue parametersReturn addressesAll of the above9The stack is used implicitly by all Turbo Pascal programs3Which of the following tend to eat up stack memory?Large local variablesLinked listsRecursive algorithmsA and C#Linked lists are stored in the heap
The Example───────────EThe example shows how the stack in your Turbo Pascal programs handlesKrecursive procedures, and how variables in those procedures are pushed ontoFand popped off of the stack.  Note where X is stored, where the returnJaddress (the line number: 6) is stored, and where the Base Pointer (BP) issaved on the stack.
Information───────────DA procedure or function that calls itself is said to be recursive.?Recursive routines must always include an "out" that allows the@routine to return, keeping the recursion from nesting endlessly,exhausting stack space.CRecursion can be both direct, in which a routine calls itself, orCindirect, in which a routine calls a second routine which in turn>calls the first routine. Indirect recursion requires a forward,declaration of one of the routines involved:   program ForwardDemo;   procedure Second; forward;   procedure First;   begin     Second;   end; { First }   procedure Second;   begin     First;   end; { Second }   begin { ForwardDemo }     First;   end. { ForwardDemo }DWithout the forward declaration of procedure Second, we couldn't useCits name in procedure First. (This program also demonstrates how toDwrite a fatally recursive program, because at runtime, the mad cycleFFirst-calls-Second-calls-First-calls-Second quickly exhausts available
stack space.)BThe following program demonstrates recursion. Procedure StackInputFcalls itself repetitively; with each invocation, a fresh copy of local=variable C goes on the stack. Once Enter (ASCII value #13) isEpressed, the stack is allowed to unwind, outputting the characters in.the reverse order in which they were received.   program RecursionDemo;   uses Crt;   procedure StackInput;   var
     C: char;   begin     C := ReadKey;!     if C <> #13 then StackInput;     Write(C);   end; { StackInput }   begin { RecursionDemo }     StackInput;   end. { RecursionDemo }KThis example demonstrates recursion. For each call to the procedure R, the\Aparameter X is pushed, followed by the return address and the BP\Fregister. These are popped when the procedure is exited. The variable\declarations are:var  Start : word;  Finish : word;7How many times can a procedure call itself recursively?Limited only by stack space	256 times16 times+Zero times; only a function can call itselfAThe stack holds return addresses, local variables, and parameters"A recursive procedure or function:Must be forward declared=Must have a way to finally return or stack space will fill upCannot declare local variables6No special checking is performed on recursive routines8Invoking:  procedure Test; begin Test; end;  will cause:A compiler errorAn I/O errorA stack overflow error"Test to execute once and then exit,Uncontrolled recursion exhausts stack memory
The Example───────────LNote that P will not have a useful value until it is initialized by pointingIit to either X (P := @X) or Y (P := @Y).  Once it has been initialized toIpoint to a variable, see how changing the variable or P^ will update boththe variable and P^.
Information───────────GA pointer is a variable that holds the address of a variable. InsteadHof data, a pointer variable contains the address of data. A pointer isDsaid to "point to" a variable. Pointers are generally used to accessCdynamically created data objects; that is, those created at runtimewith the New procedure.FPointer types are declared by including a caret (^) before the name ofsome other type, like this:   type!     <pointerType> = ^<someType>;For example:   type     IntegerPtr = ^integer;   var     IP : IntegerPtr;GType IntegerPtr is called a pointer type; when we declare variable IPCto be of type IntegerPtr, we are saying that IP points to integers,Abut isn't itself an integer. This means you can't blithely assign:numbers to it. For example, this assignment won't compile:   IP := 16;EWhat you can assign to pointer variables is addresses. One way toGget an address is to use the address operator (@) on a variable. If XCis an integer variable, then @X represents the address in memory atDwhich X is stored, and this value can be assigned to IP. Another way@is to pass a pointer variable to the New procedure. For example:   New (IP);Ballocates 2 bytes from the heap and assigns the address of these 2;bytes to IP (more on this in the Heap Allocation exercise).Dereferencing PointersDA pointer variable can be treated as though it was a variable of theCtype it points to by putting a caret after its identifier. So if IPhas type ^integer, then:    IP is a pointer    IP^ is an integerCThe NIL reserved word can be assigned to any pointer variable; itBsignifies that the pointer in question does not currently point toFanything. Typically, one assigns NIL to a pointer variable whenever itFis deallocated or as part of program initialization. This allows otherEparts of the program to check its value against NIL before attemptingto dereference it.   program PointerExample;   type     Ptr = ^integer;   var     N,M: integer;     P1, P2: Ptr;   beginD     N := 6;          { A normal assignment to an integer variable }J     P1 := N;         { Illegal and won't compile; the types don't match }@     P1 := @N;        { P1 now holds the address of variable N }"     Writeln(P1^);    { Prints 6 }"     P2 := P1;        { P2 --> N }-     M := P2^;        { Like saying M := N; }"     Writeln(M);      { Prints 6 }8     Writeln(P2);     { Illegal--can't print addresses }   end. { PointerExample }KThis example demonstrates some of the operations that can be performed on \3pointers. The variable declarations are as follows:var  X, Y : integer;  P : ^integer;HWhich type is most important when using dynamically allocated variables?integerssetspointersarrays of pointersNew returns a memory address*What data type can a pointer NOT point to?setuser-definedrecord$a pointer can point to any data type>Every variable is allocated space at a specific memory address$A NIL pointer can be used to access:RAM (Random-access memory)ROM (Read-only memory)RUM (Rarely used memory)Nothing-Sorry, no hint is available for this question3Pointer variables are initialized to NIL at runtimeTrueFalse(Turbo Pascal never initializes variablesExecuting:   New(P)   will:Allocate 8 bytesAllocate SizeOf(P^) bytesAllocate SizeOf(P) bytesAllocate 4 bytes;New allocates a block large enough to hold what P points toACompiling with {$R+} traps runtime errors because of bad pointersTrueFalse{$R+} turns on range-checking
The Example───────────JTry the different procedures to see how they allocate and dispose of spaceDon the heap.  The last four menu choices are not actual Turbo PascalIprocedures.  They are in this example to help you clean up the heap if P1Land P2 get changed to useless values, which is not hard to do. (Just as it'sDnot hard to mess up the heap in a Turbo Pascal program if you're not	careful!)
Information───────────FWhen a program created by Turbo Pascal first begins to run, a block ofEmemory known as the heap is reserved for its use. The heap allows aCprogram to create variables at runtime, rather than having them allBpreallocated at compile-time. For example, a program can create anCarray on the heap that's exactly as large as it needs to be to work$with the file it's given at runtime.FIf a routine finishes with a block before the program terminates, thenFa mechanism exists to give the memory back to the heap in case another@routine needs it later on.  The keys to using and returning heapKmemory are Turbo Pascal's New and Dispose procedures. The New procedureEis passed a pointer variable and allocates a block from the heap justAlarge enough for the type of structure the pointer points to; theEpointer variable returns with the address of this block. For example:   New (pi);Awhere pi is a pointer to an integer allocates 2 bytes of heap and%sets pi to the address of this block.   New (ptrBigArray);DThis example (where ptrBigArray is a pointer to a 1000-element arrayEof integers) allocates 2000 bytes on the heap and sets ptrBigArray topoint to this storage.CTo release a heap block after you're through with it, call Dispose,Apassing it a pointer to the block to be deallocated. For example:   Dispose (ptrBigArray);Freturns the block allocated in the earlier example to the heap so thatit can be reused if needed.BIf a program isn't going to be using the heap, its runtime storageDrequirement can be reduced by choosing to allocate little or no heap!space from the Options/Heap menu.MThis example shows how heap allocation works. The variable declarations are \as follows:var  P1, P2 : ^integer;  X : word;6What data type does the heap function MemAvail return?pointerwordintegerlongint:MemAvail returns the number of bytes available on the heapBWhich routine should be used to check for room before calling New?MaxAvailMemAvail	HeapAvailSizeOf@MaxAvail returns the # of contiguous bytes available on the heap1Given: var P : ^real,  then executing:   New (P):Is illegal and won't compileAllocates 6 bytes of heap spaceAssigns an address to PB and C=New allocates heap space and assigns to its pointer parameter
The Example───────────GInsert some nodes into the linked list.  Note the procedure for walkingHthrough the list: Point P to the same place as Header (P := Header), andIthen move to the next node (P := P^.Next) until you are at the end of theKlist. Notice that when you delete a node, P needs to be reinitialized since<it is now pointing to an area of memory that has been freed.
Information───────────ELinked lists are an efficient means for storing data, especially inDsituations in which you don't know ahead of time how many items will
need storing.FA linked list consists of one or more "nodes" allocated in the heap,@each containing a pointer to the next node in the list. The link&pointer in the last node contains nil.>The following program demonstrates a typical linked list. EachBvariable of type check contains a pointer to another check record.CThis means that once you've allocated space in the heap for a checkFrecord, some of that space can be used for a pointer to the next blockin the heap.<Note that this program declares only 5 bytes worth of global
variables.   program LinkedListDemo;   type     checkPtr = ^check;     check = record       number: integer;       amount: real;-       date: string[8];  { e.g., '07/04/88' }       payee: string[40];       next: checkPtr;	     end;   var     anchor: checkPtr;     command: char;.   procedure CollectCheckInfo(var chk: check);   begin     with chk do
     begin5       Write('Enter check number: '); Readln(number);/       Write('Enter amount: '); Readln(amount);+       Write('Enter date: '); Readln(date);-       Write('Enter payee: '); Readln(payee);       Writeln;     end; { with }   end; { CollectCheckInfo }   procedure BuildList;   var     p: CheckPtr;   begin     anchor := nil;     repeat9       Write('Enter C)heck or Q)uit: '); Readln(command);"       if command = 'Q' then Exit;       if anchor = nil then       begin         New(Anchor);         p:=Anchor;
       end       else       begin         New(p^.next);         p := p^.next;       end;       CollectCheckInfo(p^);       p^.next := nil;     until false;   end; { BuildList }   procedure ReadList;   var     p: CheckPtr;   begin     p := anchor;     while p <> nil do
     begin+       Writeln('Check number: ',p^.number);0       Writeln('Amount:       ',p^.amount:10:2);)       Writeln('Date:         ',p^.date);*       Writeln('Payee:        ',p^.payee);3       Writeln('--------------------------------');       p := p^.next;	     end;   end; { ReadList }   begin { LinkedListDemo }     BuildList;     ReadList;   end. { LinkedListDemo }KThis example shows how linked lists work. The variable declarations are as\follows:type  NodePtr = ^Node;  Node = record    Value : byte;    Next : NodePtr;  end;var  X : byte;Linked lists are good for: Storing variable amounts of dataKeeping data in sort-order2Minimizing a program's global storage requirementsAll of the above7An empty linked list requires 4 bytes of global storageLinked lists are stored in:Global variable storage	The stackThe heapBThe size of linked lists is only limited by your computer's memory.Linked lists are quicker to search than arraysTrueFalseITo search a linked list, you start at the beginning and search one-by-one
The Example───────────JType in different sequences of characters to see how they are added to theFtree, and see how the tree is searched for a character.  Note that anyHcharacters that would be added below the levels of the tree shown on thescreen will not be added.
Information───────────ASearching algorithms are used to locate a specific value (usually
in an array).Sequential SearchEThe most straightforward method is to start with the first element inAthe list and examine value after value until you either find yourEnumber or come to the end. With certain data structures (e.g., linkedFlists) a sequential approach is your only option, since there's no way$to jump into the middle of the list.?For example, if you're looking for a given integer value in theCinteger array List [1..LISTMAX]. Your routine might look like this:A   function Found(Value : integer; var Indx : integer) : Boolean;   var     Flag : Boolean;   begin     Flag := False;     Indx := 1;,     while not Flag and (Indx <= ListMax) do.       if List[Indx] = Value then Flag := True       else Indx := Indx + 1;     Found := Flag   end; { Found }EThis function returns True if Value is found in List and sets Indx tothe appropriate location.
Binary Search?For sorted arrays, there's a much better approach to searching.?Instead of starting to the left and working right, start in theFmiddle. If you happen to hit the exact value you want, you're done. IfBthe value you find in the middle is larger than your target value,Bthen you know to search the left half; otherwise, search the rightDhalf. Repeat this process on the appropriate half until you find the:value or run out of lists (meaning the value isn't there).EThis is called a binary search--a zeroing-in process that resembles:the way human beings find words in a dictionary. Here's animplementation:B   function BFound(Value : integer; var Indx : integer) : boolean;   var     Left,Right    : integer;   begin"     Left  := 1; Right := ListMax;     repeat$       Indx := (Left + Right) div 2;!       if Value < List[Indx] then         Right := Indx - 1       else Left  := Indx + 12     until (Value = List[Indx]) or (Left > Right);     BFound := (Left <= Right)   end; { BFound }Binary TreesCLike linked lists, binary trees are data structures consisting ofCmultiple "nodes," heap-allocated record variables containing data>as well as pointers to additional nodes of the same type. In a@linked list, each node points ahead to a single node. In a tree,@each node can point ahead (or, more typically, "down") to two ormore nodes.>The root of a tree is its topmost node. Except for the root,Aevery node has a parent (the node directly above it).A node canEhave siblings (other nodes pointed to by its parent) and children,(nodes directly below it that it points to).EThe most common tree is a binary tree, each node of which has at mostEtwo subtrees attached to it. Usually, these subtrees are labeled asAleft and right. You could use the following node definition for abinary tree:   type     NodePtr = ^Node;     Node = record       Data : integer;       Left,Right : NodePtr	     end;FEach node points to its children (the nodes directly below it), with a'value of nil indicating an unused link.MThis example shows how binary trees work. Note that you will not be able to \Madd any nodes below the bottom of the screen. The variable declarations are \as follows:var  C : char;4A sequential search on a 100 element array requires: A worst case of 100 examinationsA worst case of 10 examinationsAn average of 50 examinations$An average of Log2(100) examinationsA and C5a sequential search looks at each element in sequence7A binary search on a 100 element sorted array requires:No more than 7 examinationsOn average, 50 examinationsNo more than 100 examinations
Log2(128) = 7$A binary search routine can process:A sorted linked listA sorted array	Any array<A binary search resembles looking up words in the dictionaryA node of a binary tree$Is usually allocated in stack memory%Contains pointers to additional nodes Can have two or more child nodes2Binary trees are a special class of tree structure2Which of the following is true about binary trees?5They are efficiently searched by recursive algorithmsAThey make more efficient use of memory than standard linked lists-They use hashing techniques for key retrievalAll of the above4Each branch of a binary tree is itself a binary tree