DelphiBasics Home  |  Programming logic
 Documents Tutorials Writing your first program  Writing your second program  Amending this program   Delphi data types    Numbers    Text    Sets and enumerations    Arrays    Records   Programming Logic    Looping    SubRoutines    Exception handling   Dates and times   Files   Pointers   Printing text and graphics   Object Orientation basics    Memory leaks!    Inheritance    Abstraction    Interfaces    An example class References Standard components Articles Learn to program in Pascal - online education course Castalia for Delphi  A brief history of Delphi   Usability : file handling  Usability : reference books Author links
Programming logic
What is programming logic?
Programming in Delphi or any other language would not work without logic. Logic is the glue that holds together the code, and controls how it is executed. For example, supposing we were writing a word procesor program. When the user presses the Enter key, we will move the cursor to a new line. The code would have a logical test for the user hitting the Enter key. If hit we do a line throw, if not, we continue on the same line.

If then else
In the above example, we might well use the If statement to check for the Enter key.

Simple if then else
Here is an example of how the if statement works:

 ` var   number : Integer;   text   : String; begin   number := Sqr(17);          // Calculate the square of 17   if number > 400                      then text := '17 squared > 400'    // Action when if condition is true   else text := '17 squared <= 400';  // Action when if condition is false end;`

 ` text is set to : '17 squared <= 400'`

There are a number of things to note about the if statement. First that it spans a few lines - remember that Delphi allows statements to span lines - this is why it insists on a terminating ;

Second, that the then statement does not have a terminating ; -this is because it is part of the if statement, which is finished at the end of the else clause.

Third, that we have set the value of a text string when the If condition is successful - the Then clause - and when unsuccessful - the Else clause. We could have just done a then assignment:

 `   if number > 400                      then text := '17 squared > 400';`

Note that here, the then condition is not executed (because 17 squared is not > 400), but there is no else clause. This means that the if statement simply finishes without doing anything.

Note also that the then clause now has a terminating ; to signify the end of the if statement.

Compound if conditions, and multiple statements
We can have multiple conditions for the if condition. And we can have more than one statement for the then and else clauses. Here are some examples:

 `   if (condition1) And (condition2)   // Both conditions must be satisfied   then     begin       statement1;       statement2;       ...     end              // Notice no terminating ';' - still part of 'if'   else     begin       statement3;       statement4;       ...     end;`

We used And to join the if conditions together - both must be satisfied for the then clause to execute. Otherwise, the else clause will execute. We could have used a number of different logical primitives, of which And is one, covered under logical primitives below.

Nested if statements
There is nothing to stop you using if statements as the statement of an if statement. Nesting can be useful, and is often used like this:

 `   if condition1    then statement1   else if condition2        then statement2        else statement3;`

However, too many nested if statements can make the code confusing. The Case statement, discussed below, can be used to overcome a lot of these problems.

Logicial primitives
Before we introduce these, it is appropriate to introduce the Boolean data type. It is an enumerated type, that can have one of only two values : True or False. We will use it in place of a condition in the if clauses below to clarify how they work:

 ` begin   if false And false   then ShowMessage('false and false = true');    if true And false   then ShowMessage('true  and false = true');    if false And true   then ShowMessage('false and true  = true');    if true And true   then ShowMessage('true  and true  = true');    if false Or false   then ShowMessage('false or  false = true');    if true Or false   then ShowMessage('true  or  false = true');    if false Or true   then ShowMessage('false or  true  = true');    if true Or true   then ShowMessage('true  or  true  = true');    if false Xor false   then ShowMessage('false xor false = true');    if true Xor false   then ShowMessage('true  xor false = true');    if false Xor true   then ShowMessage('false xor true  = true');    if true Xor true   then ShowMessage('true  xor true  = true');    if Not false   then ShowMessage('not false  = true');    if Not true   then ShowMessage('not true  = true'); end;`

 ` true  and true  = true false or  true  = true true  or  false = true true  or  true  = true false xor true  = true true  xor false = true not false = true`

Note that the Xor primitive returns true when one, but not both of the conditions are true.

Click on the primitives in blue above to learn how they can also be used for mathematical (bitwise) calculations.

Case statements
The If statement is useful when you have a simple two way decision. Ether you go one way or another way. Case statements are used when you have a set of 3 or more alternatives.

A simple numerical case statement
 ` var   i : Integer; begin   i := RandomRange(15,20);  // Generate a random number from 15 to 20   Case i of     15 : ShowMessage('Random number was fifteen');     16 : ShowMessage('Random number was sixteen');     17 : ShowMessage('Random number was seventeen');     18 : ShowMessage('Random number was eighteen');     19 : ShowMessage('Random number was nineteen');     20 : ShowMessage('Random number was twenty');   end; end;`

 ` Random number was fifteen`

The RandomRange routine generates a random number between two given values. However, each time you run the program, it will always start with the same pseudo random value (unless you use RandomSeed).

The case statement above routes the processing to just one of the statements. OK, the code is a bit silly, but it is used to illustrate the point.

Using the otherwise clause
Supposing we were not entirely sure what value our case statement was processing? Or we wanted to cover a known set of values in one fell swoop? The Else clause allows us to do that:

 ` var   i : Integer; begin   i := RandomRange(10,20);  // Generate a random number from 10 to 20   Case i of     15 : ShowMessage('Random number was fifteen');     16 : ShowMessage('Random number was sixteen');     17 : ShowMessage('Random number was seventeen');     18 : ShowMessage('Random number was eighteen');     19 : ShowMessage('Random number was nineteen');     20 : ShowMessage('Random number was twenty');   else     ShowMessageFmt('Unexpected number : %d',[i]);   end; end;`

 ` Unexpected number : 10`

Using enumeration case values
Just as with the If statement, the Case statement may use any ordinal type. This allows us to use the very readable enumeration type:

 ` type   TCar = (Nissan, Ford, Rover, Jaguar);    // An enumeration type var        car : TCar;                              // An enumeration variable begin   car := Rover;                            // Set this variable   case car of     Nissan : ShowMessage('We have a Nissan car');     Ford   : ShowMessage('We have a Ford car');     Rover  : ShowMessage('We have a Rover car');     Jaguar : ShowMessage('We have a Jaguar car');   end; end;`

 ` We have a Rover car`

Looping
The conditional statements above allow us to act differently depending on data values. Another form of decision making is the repetitive action. Here we repeat a set of statements a fixed or variable number of times. This topic is discussed in the Looping tutorial.

'
'
'