📄 ch02.htm
字号:
if statements testing for different values of the same variable, it might be a candidate for a case statement. The case statement is discussed later in this chapter in the section "The case Statement." <HR></BLOCKQUOTE><P>So far I have used only one conditional expression in the if examples I have givenyou. When you have just one conditional expression, you can use parentheses aroundthe expression or not use parentheses as you see fit. If, however, you have morethan one conditional expression, you must surround each conditional expression withparentheses. For example:</P><P><PRE>if (X = 20) and (Y = 50) then DoSomething;</PRE><P>If you forget the parentheses, the compiler will, of course, let you know by issuinga compiler error.</P><P>The if statement is heavily used in Object Pascal programming. It's straightforward,so you won't have any trouble with it. The main thing is keeping all the begin andend keywords straight!</P><P><H4>The if...then...else Statement, Form 1</H4><PRE>if <I>cond_expr</I> then <I>true_statement</I>else <I>false_statement</I>;</PRE><P>If the conditional expression <I>cond_expr</I> is True, the line of code representedby <I>true_statement</I> is executed. If the optional else clause is specified, theline of code represented by <I>false_statement</I> is executed when the conditionalexpression <I>cond_expr</I> is False.</P><P><H4>The if...then...else Statement, Form 2</H4><PRE>if <I>cond_expr_1</I> then begin <I>true_statements</I>;end else begin <I>false_statements</I>;end;</PRE><P>If the conditional expression <I>cond_expr_1</I> is True, the block of code representedby <I>true_statements</I> is executed. If it is False, the block of code representedby <I>false_statements</I> is executed.</P><P><H2><A NAME="Heading5"></A>Using Loops</H2><P>The loop is a common element in all programming languages. A loop can be usedto iterate through an array, to perform an action a specific number of times, toread a file from disk...the possibilities are endless. In this section, I will discussthe for loop, the while loop, and the repeat loop. For the most part they work invery similar ways. All loops have these common elements:</P><UL> <LI>A starting point <P> <LI>A body, usually enclosed in begin and end keywords, that contains the statements to execute on each pass <P> <LI>An ending point <P> <LI>A test for a condition that determines when the loop should end <P> <LI>Optional use of the Break and Continue procedures</UL><P>A <I>loop</I> is an element in a programming language that is used to performan action repeatedly until a specific condition is met.</P><P>The starting point for the loop is one of the Object Pascal loop statements (for,while, or repeat). The body contains the statements that will execute each iterationthrough the loop. The body can contain any valid Object Pascal code and can be asingle line of code or multiple lines of code. If the body contains multiple linesof code, the code must be blocked with begin and end statements (with the exceptionof the repeat loop). The ending point for the loop is either the end keyword (inthe case of the for loop and the while loop) or the until keyword (in the case ofthe repeat loop). When the body of a loop is a single line of code, the begin andend keywords are not required.</P><P>Most loops work something like this: The loop is entered and the test conditionis evaluated. If the test condition evaluates to False, the body of the loop is executed.When program execution reaches the bottom of the loop, it jumps back to the top ofthe loop where the test condition is again evaluated. If the test condition is stillFalse, the whole process is repeated. If the test condition is True, program executionjumps to the line of code immediately following the loop code block. The exceptionto this description is the repeat loop, which tests for the condition at the bottomof the loop rather than at the top.</P><P>The test condition tells the loop when to stop executing. In effect the test conditionsays, for example, "Keep doing this until <I>X</I> is equal to 10," or"Keep reading the file until the end-of-file is reached." After the loopstarts, it continues to execute the body of the loop until the test condition evaluatesto True.</P><BLOCKQUOTE> <P><HR><strong>CAUTION:</strong> It's easy to accidentally write a loop so that the test condition never evaluates to True. This will result in a program that is locked up or hung. Your only recourse at that point is to press Ctrl+Alt+Del and kill the task. The Windows Close Program box (or the Windows NT Task Manager) will come up and display the name of your program with (Not Responding) next to it. You'll have to select your program from the list and click End Task to terminate the runaway program. <HR> <P><HR><strong>TIP:</strong> In Delphi you typically run a program using the Run button on the toolbar or by pressing F9. If you need to kill a runaway program that was run from the IDE, you can choose Run | Program Reset from the main menu or press Ctrl+F2 on the keyboard. Note, however, that Windows 95 does not like you to kill tasks with Program Reset and might crash if you reset a program several times (Windows NT is much more forgiving in this area). Always run your programs to completion if possible, especially when developing on the Windows 95 platform. <HR></BLOCKQUOTE><P>Given that general overview, let's take a look at each type of loop individually.</P><P><H2><A NAME="Heading6"></A>The for Loop</H2><P>The for loop is probably the most commonly used type of loop. It takes two parameters:the starting value and ending value. If the loop is to count up, the to keyword isused. If the loop is to count backward, then the downto keyword is used.</P><P><H4>The for Loop Statement, Counting Up</H4><PRE>for <I>initial_value</I> to <I>end_value</I> do begin <I>statements</I>;end;</PRE><P>The for loop repeatedly executes the block of code indicated by <I>statements</I>until the ending value <I>end_value</I> is reached. The state of the loop is initializedby the statement <I>initial_value</I>. The variable indicated in <I>initial_value</I>is incremented by one each iteration through the loop. If the body of the loop isa single statement, the begin and end statements are not required.</P><P><H4>The for Loop Statement, Counting Down</H4><PRE>for <I>initial_value</I> downto <I>end_value</I> do begin <I>statements</I>;end;</PRE><P>The for loop repeatedly executes the block of code indicated by <I>statements</I>until the ending value <I>end_value</I> is reached. The state of the loop is initializedby the statement <I>initial_value</I>. The variable indicated in <I>initial_value</I>is decremented by one each iteration through the loop. If the body of the loop isa single statement, the begin and end statements are not required.</P><P>As most syntax statements are somewhat vague, some examples will probably help.First, take a look at a typical for loop that counts up:</P><P><PRE>var I : Integer;begin for I := 0 to 9 do begin Memo1.Lines.Add(`This is iteration ` + IntToStr(I)); end;end;</PRE><P>This code will result in the statement inside the braces being executed 10 times.The first parameter, I := 0, tells the for loop that it is starting with an initialvalue of 0. The second parameter, 9, tells the loop to keep running until the variableI equals 9. The to keyword specifies that the value of I should be incremented byone each time the loop executes.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> The use of the variable name I has its roots in the FORTRAN language and is traditional in for loops. Naturally, any variable name can be used, but you will often see I used in for loops. <HR></BLOCKQUOTE><P>Let's look at a variation of this code. The following code snippet will achieveexactly the opposite effect as the first example:</P><P><PRE>var I : Integer;begin for I := 9 downto 0 do begin Memo1.Lines.Add(`This is iteration ` + IntToStr(I)); end;end;</PRE><P>This time I'm starting with 9 and stopping when I is equal to 0. The downto keywordspecifies that the value of I should be decremented each time the loop executes.This is an example of a loop that counts backward.</P><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> In the preceding examples, the begin and end keywords are not strictly required. If begin and end are not used, the statement immediately following the for statement is considered the body of the loop. It's up to you whether you use begin and end on single statements, although it's considered bad form to do so. <HR></BLOCKQUOTE><P><H4>A Sample for Loop</H4><P>Let's write a little program that illustrates the use of the for loop. In doingso, I will explain another Delphi component, the Memo component (used earlier inthis chapter). Perform these steps:</P><DL> <DT></DT> <DD><B>1. </B>Begin with a new application (File | New Application). <P> <DT></DT> <DD><B>2. </B>Place a button on the form. <P> <DT></DT> <DD><B>3. </B>Locate the Memo component on the Standard tab of the Component palette (it should be just to the left of the Button component). Click the button, and then click on the form. A memo will be placed on your form. <P> <DT></DT> <DD><B>4. </B>Make the memo larger by dragging the black sizing rectangle in the lower-right corner of the memo. <P> <DT></DT> <DD><B>5. </B>Double-click the button to create an OnClick event handler for the button. Enter code so that the event handler looks like this: <P></DL><BLOCKQUOTE> <PRE>procedure TForm1.Button1Click(Sender: TObject);var I : Integer;begin Memo1.Lines.Clear; for I := 0 to 5 do Memo1.Lines.Add(`This is iteration ` + IntToStr(I));</PRE> <PRE>Memo1.Lines.Add(`'); for I := 5 downto 0 do Memo1.Lines.Add(`This is iteration ` + IntToStr(I));end;</PRE></BLOCKQUOTE><PRE></PRE><P>Run the program. When you click the button, lines of text are added to the memo.Figure 2.1 shows this program running.</P><P>As I said earlier, the loop variable will be incremented by one each time throughthe loop. Unlike other programming languages, Pascal doesn't provide a way of iteratingthrough a for loop by a value other than one. For example, there is no way to iteratethrough a for loop from 0 to 100 by 10s. To accomplish this, you must make use ofanother variable as follows:</P><P><PRE>var I : Integer; X : Integer;begin X := 0; Memo1.Lines.Clear; for I := 0 to 9 do begin Memo1.Lines.Add(`Iteration value: ` + IntToStr(X)); Inc(X, 10); end;end;</PRE><P>This code will display this in the memo:</P><P><PRE>Iteration value: 0Iteration value: 10Iteration value: 20Iteration value: 30Iteration value: 40Iteration value: 50Iteration value: 60Iteration value: 70Iteration value: 80Iteration value: 90</PRE><P><A HREF="javascript:popUp('28670201.gif')"><B>FIGURE 2.1.</B></A><B> </B><I>Theoutput from the for loop exercise.</I></P><P><PRE><I></I></PRE><BLOCKQUOTE> <P><HR><strong>NOTE:</strong> Notice the use of the Inc function in the preceding snippet. This function increments the given variable (X in this example) by the specified value (10). If Inc is used without an increment parameter, the variable is incremented by one. For example:</P> <PRE>Inc(X); { X is incremented by one. Same as X := X + 1 }</PRE></BLOCKQUOTE><PRE></PRE><BLOCKQUOTE> <P>Inc has a companion function called, predictably, Dec. Here are examples of the Dec function:</P> <PRE>Dex(X); { X is decremented by one }Dec(X, 10); { X is decremented by 10 }</PRE></BLOCKQUOTE><PRE></PRE><BLOCKQUOTE> <P>Use of Inc and Dec is preferred over the long version (X := X + 1, for example). <HR></BLOCKQUOTE><PRE></PRE><H4>The Pred and Succ Functions</H4><P>You will often see the Pred and Succ functions used with for loops. The Pred functionreturns the predecessor of the passed argument. For example, Pred(10) will returnthe value 9, Pred(100) will return 99, and so on. Given that information, the followingthree for loops are identical:</P><P><PRE>var X : Integer;begin X := 10; for I := 0 to 9 do DoSomething; for I := 0 to X - 1 do DoSomething; for I := 0 to Pred(X) do</PRE><PRE>DoSomething;</PRE><PRE>end;</PRE><P>When you start with an initial value of 0, it's natural to make the mistake ofdoing one too many iterations in a loop. Using the Pred function solves this problemand is a bit more elegant than using X - 1. The Succ function, naturally, returnsthe successor of the argument passed. This is useful when counting backward:</P><P><PRE>for I := 100 downto Succ(X) do DoSomething;</PRE><P>Now that you've seen the for loop in action, it won't be too difficult to applythe same concepts to the while and repeat loops. Let's take a look at those now.</P><P><H3><A NAME="Heading7"></A>The while Loop</H3>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -