Delphi Programming for Beginners - Lesson 7

Minimum of Object Pascal Part Two

Flow of a programme

A programmer has to be able to somehow control the flow of the programme and he has several ways how to do that:

  • Loops
  • Conditions
  • Calling subprogrammes

Conditions

We basically have two options, a command IF and CASE.

If condition

if boolean-expression then 
        command1	
else 
        command2;

where both commands can be complicated commands having begin and end and where you don’t have to include else part.

Case command

case OrdinalType of 
Item1: Command1; 
Item2, Item3: Command2; 
Item4..Item9: Command3; 
else 
   Command4;
 end;

The argument can be an interval as well (Item4..Item9 in example above).

Three types of loops - While, Repeat..Until and For Repeat..Until

Repeat
   Command1
   Command2
   ...
   CommandX
Until expression

If expression returns True, the loop will end. Important thing is that we test the condition AFTER evaluation of a body. That means we evaluate the body at least once.


Repeat
 Write('Insert value (0..9): ');
 Readln(I);
until (I >= 0) and (I <= 9);
While

Let’s look at the following example. Imagine we have a variable called number and we put 1 into it. This is our code:


While number <= 100 do
begin
 number:= number +1;
end;

On the first line we check whether value saved in variable number is either smaller or equal to 100. If the value is bigger than 100, we would just completely skip the following code and we would continue on the first line after „end“ line. But because 1 is smaller or equal to 100, we proceed to evaluate the body. In this particular example we increase a value of number by one. After we evaluate the body, we go back to „while“ line and we test the condition again. And we will do that until we get to the point the number is bigger than 100. Generally, we can say:


While condition do
Begin
   Command1
   Command2
   ...
   ComandX
End

what means, as long as condition is equal to „True“, we will evaluate the body.

For

This loop requires a concrete amoung of iterations. Let’s again look at a simple example:


For i:=1 to 5 do
Begin
   ShowMessage(‘Number‘ + IntToStr(i));
End;

So, what did we do here? On the first line we do 2 things:

  • We kind of determine how many iterations we go through
  • We put value 1 into I variable (although you don’t have to call it I, it can be pretty much anything) as that is the initial value

Then, we proceed to execute the body and after we do so, we go back to the first line and we raise the value of i by 1 and if the value of i is smaller or equal to 5 (which is the kind of the final value of i), we execute the body again, until i is bigger than 5.

Generally,


For variable:= startingValue to finalValue do
Begin
 Unlimited amount of commands
End;

Where startingValue is smaller (or equal) to finalValue. Or, instead of rising the value of variable, we can decrease it as well:


For variable:=startingValue downto finalValue.

And now, finalValue is the smaller one. Example:


For variable:= 10 downto 1

Simply rule says: If you want to go up, use to. If you want to go down, use downto.

For-in

Newer Delphis can use for loop as an iteration through another type (string, set, an array or collection like TList).


var 
   C: Char; 
   S1, S2: String; 
begin 
   S1 := 'helloWorld’;
   for C in S1 do 
      S2 := S2 + C; 
end;

In example above, we have 3 variables: C of type Char and strings S1 and S2. In the beginning, we give string S1 value „helloWorld“. And then, in every iteration we give C a value of each letter in string S1. And on the following line, we add this letter to what we already have saved in S2. By the end of the programme, both S1 and S2 will have value „helloWorld“.

Calling subprogrammes

Subprogrammes (procedures and functions) are used for improving readability, reusability of code etc. Generally we try to keep each part of the programme to be no longer than one page. If a code grows over a page, you should consider dividing the code into procedures. A procedure or a function can have arguments, function can even have a return value. Arguments can be pretty much of any type (including complicated data types such as record or array).

Declaration:


procedure nameOfProcedure  (argument1, argument2,….,argumentx);
function nameOfFunction(argument1, argument2,…,argumentx):type;

where argument1 is a specification of an argument (name:type), for example s:string so a compilator knows how to work with this variable.


procedure Test(const s1:string; var i2:Integer; s3: string);
begin
 s1 – can’t be changed and also const gives a compilator hint that it can be well optimalized
 i2 – variable can be changed and its value is moved into called code
 s3 – variable can be changed, but its value will be lost in the end
end;

Argument i2 is handed by reference while s1 and s3 by value.
A return value is represented by a variable Result or by an argument exit.


function Sum(i1, i2: Integer):Integer;
begin
 Result := i1 + i2;
//or exit i1+i2;
end;
Methods

If a procedure or a function is defined within a class, it’s called a method. Here's small useful selection of procedures and functions from the SysUtils unit:


Abort 
- silent exception, termination of actually executed action
CreateDir 
- creates a given directory: CreateDir('C:\test');
CurrToStr, FloatToStr 
- conversion from Currency/Float to String
Date 
- returns actual system date
DateTimeToStr, DateTimeToString, DateToStr 
- conversion of TDateTime to String
DayOfWeek 
- returns day index within a week, starting with Sunday
DecodeDate, DecodeTime 
- disassembles TDateTime value to numeric parts
DeleteFile 
- deleting of a file
DirectoryExists 
- checks if given directory exists
EncodeDate, EncodeTime 
- assembles TDateTime from numeric parts
ExtractFileExt, ExtractFileName, ExtractFilePath 
- returns extension, name and path from file path
FileExists 
- checks if given file exists
FindFirst, FindNext, FindClose 
- searching for the file (object approach in newer Delphis is a better way
ForceDirectories 
- creates full directory path
Format 
- efficient formatting of strings: Format(‘Number: %d’, [i]);
FreeAndNil 
- releasing object and its setting to nil
IntToHex, IntToStr 
- converts Integer to String or to String as a hex
IncMonth 
- increases TDateTime for given number of months (use negative value for decreasing)
LowerCase, AnsiLowerCase 
- converts strings (ansistrings) to lowercase
Now - returns actual system time
QuotedStr 
- returns given string in quotas, e.g. for its using in SQL script
StrToInt, StrToIntDef 
- converts string to Integer or to Integer with default value (eliminates exception by wrong input)
Trim, TrimLeft, TrimRight 
- removes spaces from the String value (entire string, from the left/right side)
ChDir 
- changes actual directory
MaxInt, MinInt 
- span of Integer value
MkDir 
- creates directory
Pos 
- checks if given substring exists within string: if Pos(' ', S) > 0 then
Random 
- returns random number (needs initialiyation using Randomize procedure)
StringOfChar 
- creates string from given char and its count:( StringOfChar('A', 10); => ‘AAAAAAAAAAAA’
Copy 
- returns substring from given string: 
s := ‘text item’;
s2 := copy(s, 2, 4); // returns xt i

Procedures and functions described above represent only very small figure of available ones. However, some tasks can be made better using object approach, for instance if we need to work with fiels and directories, using TPath, TDirectory and TFile from IOUtils is recommended. Homework

Put 3 TEdits and a button on a form. After pressing a button:

  • Current date is saved as a string and the first 3 symbols fill the first edit
  • Second edit: hex value of the highest integer value found out programatically
  • Retrieve a text from third editbox and try to save it as a number
  • If a number is smaller than 10, show message „value is smaller than 10 (xx)“
  • If the number is somewhere between 10 and 100, show message „value is in interval 10-100 (xx)“
  • If the number is bigger than 100, show message „value is bigger than 100 (xx)“
  • Invalid value -> invalid value
  • Instead of „xx“ show the value the user typed in
  • Use case and StrToInt or StrToIntDef
  • Test your code for these texts: 1,10,99,100,-1,te02

About the Author

Ing. Radek Červinka
Embarcadero MVP
Web: Delphi.cz
Twitter: @delphi.cz