home   Java Script   MS Access   Perl   HTML   Delphi   C ++   Visual Basic   Java   CGIPerl   MS Excel   Front Page 98   Windows 98   Ms Word   Builder   PHP   Assembler     Link to us   Links    



Teach Yourself Borland Delphi 4 in 21 Days

Previous chapterNext chapterContents


- 2 -

More on Pascal


You now have a pretty good start on learning Object Pascal. In this chapter, you will continue to learn about the Object Pascal language by examining more of the fundamentals of Object Pascal. Today you will learn about

if, then, else

There are some aspects of programming that are common to all programming languages. One such item that Object Pascal has in common with other programming languages is the if statement. The if statement is used to test for a condition and then execute sections of code based on whether that condition is True or False. Here's an example:

var
  X : Integer;
begin
  X := StrToInt(Edit1.Text);
  if X > 10 then 
    Label1.Caption := `You entered a number greater than 10.';
end;

This code gets the contents of an edit control and stores it in an integer variable. If the number is greater than 10, the expression x > 10 evaluates to True and the message is displayed; otherwise, nothing is displayed. Note that when the conditional expression evaluates to True, the statement immediately following the if...then expression is executed. The conditional part of an if statement is always followed by then.

New Term: The if statement is used to test for a condition and execute one or more lines of code when that condition evaluates to True.

Executing Multiple Instructions

Let's say you have multiple lines of code that should be executed when the conditional expression is True. In that case, you would need begin and end keywords to block those lines:

if X > 10 then begin
  Label1.Caption := `You entered a number greater than 10.';
  DoSomethingWithNumber(X);
end;

When the conditional expression evaluates to False, the code block associated with the if expression is ignored and program execution continues with the first statement following the code block.


NOTE: Object Pascal contains a few shortcuts. One of those shortcuts involves using just a Boolean variable's name to test for True. Look at this code:

if FileGood then ReadData;



This method is shortcut for the longer form, which is illustrated with this line:

if FileGood = True then ReadData;



This shortcut only applies to Boolean variables. You can test for False by applying the not keyword to a variable name:

var
  FileGood : Boolean;
begin
  FileGood := OpenSomeFile;
  if not FileGood then ReportError;
end;



Learning the Object Pascal shortcuts helps you write code that contains a degree of elegance. Knowing the shortcuts will also help you understand Object Pascal code that you read in examples and sample listings.


Adding else

In some cases, you might want to perform an action when the conditional expression evaluates to True and perform some other action when the conditional expression evaluates to False. You accomplish this by implementing the else statement:

if X = 20 then 
  DoSomething(X)
else
  DoADifferentThing(X);
New Term:  The else statement is used in conjunction with the if statement and identifies a section of code that is executed when the if statement fails (that is, evaluates to False).

In this example, one of the two functions will be called based on the value of X, but not both.

I want you to notice something about the preceding example. The line following the if statement does not end in a semicolon. This is because the entire if...then...else sequence is viewed as a single statement. You omit the semicolon on the first line following the if statement only if it's a single line of code (that is, you are not using begin and end following the if statement). Here are a couple of examples of legal if...then...else syntax:

if X = 20 then
  DoSomething(X)        { no semi-colon here because }
else                    { it's a single line of code }
  DoADifferentThing(X);
if X = 20 then begin
  DoSomething(X);       { semi-colon needed here because }
end else begin          { of the begin/end block }
  DoADifferentThing(X);
end;
if X = 20 then begin
  DoSomething(X);       { Multiple lines, use semi-colons }
  X := 200;             { at the end of each line. }
  Y := 30;
end else begin
  DoADifferentThing(X);
  X := 100;
  Y := 15;
end;


NOTE: It doesn't matter where you put the then, begin, and else keywords. The following two blocks of code are identical as far as the compiler is concerned:

{ One way to do it... }
if X = 20 then begin
  DoSomething(X);  
  X := 200;        
  Y := 30;
end else begin
  DoADifferentThing(X);
  X := 100;
  Y := 15;
end;
{ Same code, different layout... }
if X = 20 
then 
begin
  DoSomething(X); 
  X := 200;       
  Y := 30;
end 
else 
begin
  DoADifferentThing(X);
  X := 100;
  Y := 15;
end;



Ultimately it's up to you to decide on the coding style that you will use. While coding style is largely a matter of preference, be sure you settle on a style that makes your code easy to read.






NOTE: Remember that the equality operator is the equal sign (=) and that the assignment operator is colon-equal (:=). A common coding mistake is to use the assignment operator where you mean to use the equality operator. Fortunately, the compiler will issue an error when you do this.

Nested if Statements

You can nest if statements when needed. Nesting is nothing more than following an if statement with one or more additional if statements.

if X > 10 then
  if X < 20 then
    Label1.Caption := `X is between 10 and 20';

Keep in mind that these are simplified examples. In the real world, you can get lost in the maze of begin and end statements that separate one code block from the next. Take a look at this code snippet, for instance:

if X > 100 then begin
  Y := 20;
  if X > 200 then begin
    Y := 40;
    if X > 400 then begin
      Y := 60;
      DoSomething(Y);
    end;
  end;
end else if X < -100 then begin
  Y := -20;
  if X < -200 then begin
    Y := -40;
    if X < -400 then begin
      Y := -60;
      DoSomething(Y);
    end;
  end;
end;

Even this is a fairly simple example, but you get the idea.


[BEGTIP: When a section of code contains more than two or three consecutive 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."

So far I have used only one conditional expression in the if examples I have given you. When you have just one conditional expression, you can use parentheses around the expression or not use parentheses as you see fit. If, however, you have more than one conditional expression, you must surround each conditional expression with parentheses. For example:

if (X = 20) and (Y = 50) then
  DoSomething;

If you forget the parentheses, the compiler will, of course, let you know by issuing a compiler error.

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 and end keywords straight!

The if...then...else Statement, Form 1

if cond_expr then 
    true_statement
else
    false_statement;

If the conditional expression cond_expr is True, the line of code represented by true_statement is executed. If the optional else clause is specified, the line of code represented by false_statement is executed when the conditional expression cond_expr is False.

The if...then...else Statement, Form 2

if cond_expr_1 then begin
    true_statements;
end else begin
    false_statements;
end;

If the conditional expression cond_expr_1 is True, the block of code represented by true_statements is executed. If it is False, the block of code represented by false_statements is executed.

Using Loops

The loop is a common element in all programming languages. A loop can be used to iterate through an array, to perform an action a specific number of times, to read a file from disk...the possibilities are endless. In this section, I will discuss the for loop, the while loop, and the repeat loop. For the most part they work in very similar ways. All loops have these common elements:

A loop is an element in a programming language that is used to perform an action repeatedly until a specific condition is met.

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 iteration through the loop. The body can contain any valid Object Pascal code and can be a single line of code or multiple lines of code. If the body contains multiple lines of code, the code must be blocked with begin and end statements (with the exception of the repeat loop). The ending point for the loop is either the end keyword (in the case of the for loop and the while loop) or the until keyword (in the case of the repeat loop). When the body of a loop is a single line of code, the begin and end keywords are not required.

Most loops work something like this: The loop is entered and the test condition is 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 of the loop where the test condition is again evaluated. If the test condition is still False, the whole process is repeated. If the test condition is True, program execution jumps to the line of code immediately following the loop code block. The exception to this description is the repeat loop, which tests for the condition at the bottom of the loop rather than at the top.

The test condition tells the loop when to stop executing. In effect the test condition says, for example, "Keep doing this until X is equal to 10," or "Keep reading the file until the end-of-file is reached." After the loop starts, it continues to execute the body of the loop until the test condition evaluates to True.


CAUTION: 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.


TIP: 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.

Given that general overview, let's take a look at each type of loop individually.

The for Loop

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 is used. If the loop is to count backward, then the downto keyword is used.

The for Loop Statement, Counting Up

for initial_value to end_value do begin
    statements;
end;

T