Introduction
Object (or Delphi) Pascal, a set of object-oriented extensions to standard Pascal, is the language of Delphi. Delphi Pascal is a high-level, compiled, strongly typed language that supports structured and object-oriented design. Its benefits include easy-to-read code, quick compilation, and the use of multiple unit files for modular programming.
Borland Delphi is a sophisticated Windows programming environment, suitable for beginners and professional programmers alike. Using Delphi you can easily create self-contained, user friendly, highly efficient Windows applications in a very short time - with a minimum of manual coding.
Delphi provides all the tools you need to develop, test and deploy Windows applications, including a large number of so-called reusable components.
Borland Delphi, in it's latest version, provides a cross platform solution when used with Borland Kylix - Borland's RAD tool for the Linux platform. Borland Delphi (1/2/3/4/5) is a development tool for Microsoft Windows applications. Delphi is powerful and easy to use tool for generating stand-alone graphical user interface (GUI) programs or 32-bit console applications (programs that have no GUI presence but instead run in what is commonly referred to as a "DOS box.")
When paired with Borland Kylix, Delphi 6 users can build single-source applications for both Windows and Linux, which opens new opportunities and increases the potential return on development investments. Use the Cross-platform CLX component library and visual designers to build high-performance portable applications for Windows that can be easily re-compiled on Linux.
Delphi is the first programming language to shatter the barrier between high-level, easy-to-use rapid application development environments and low-level bits-and-bytes power tools. Delphi ships in a variety of configurations aimed at both departmental and enterprise needs. With Delphi, you can write Windows programs more quickly and more easily than was possible ever before.
Delphi can access many types of databases. Using forms and reports that you create, the BDE (Borland Database Engine) can access local databases, like Paradox and DBase, network SQL server databases, like InterBase, and SysBase, and any data source accessible though ODBC (open database connectivity).
Application vs CLX Application
With some versions of Delphi (supposed Delphi 6 Professional or Enterprise), you can build and develop cross platform applications that can be ported to Linux and compiled with Kylix. To develop a CLX application, instead of standard Windows application, you could pick CLX Application from the File | New menu. The Delphi IDE is similar to one when you build Windows applications, except that the Component palette changes dynamically to show the objects that are available for use in Linux CLX applications.
Since this course is about Delphi for the Windows platform, we will be exploring Delphi programming from that point of view. However, if you have Kylix and want to join this course you are of course encouraged to do so. Even though, my intention at this stage of this Course, is not to explain differences between CLX (Linux) and VCL (Windows) development you should know that there are no reasons why you should not join the course and just have in mind that when we talk about, let's say, form1.DFM you think form1.XFM.
Delphi vs Others
What is the BEST RAD tool for you!
"I would like to learn a visual orientated programming language but I can't choose between Delphi, Visual Basic, Java, C/C++, PowerBuilder, Clarion...." A question commonly asked by software developers. If you have ever asked yourself a question like this one (and I bet you have) than you know that there is no straight answer.
"Just for the fun of it, let's place Visual Basic, Delphi, and Oracle Power Objects side by side. Let's test development capabilities, database support, performance, and other features that really matter. May the best tool win!" From Borland.com
Visual Basic and Delphi Head to Head
"We did a side-by-side comparison of the currently shipping versions of Delphi and VB that are specifically geared toward client/server development: Borland's Delphi Client/ Server and Microsoft Visual Basic 3.0, Professional Edition." From ZDNet
Why I really like Delphi
"We are VB people, but first and foremost we are solution designers. While we may be most comfortable with Visual Basic and in spite of the Microsoft Marketing team saying we can do anything with VB, the fact is that VB has limits." From Visual Basic Developers Association
Delphi. Reasons why.
"Delphi combines much of the power of C++ with the ease that one expects (and doesn't get) of VB. Here is why..."
Rapid Application Development Tools
NSTL compared leading rapid application development (RAD) tools for Windows 95 and Windows NT. The products evaluated were Visual Basic 6.0, PowerBuilder 6.0 and Delphi 4.0.
Why shun Delphi?!
"My personal belief is that the Delphi system and its language (Borland Object Pascal) is not an appropriate system for teaching introductory programming. Readers are welcome to disagree!" From Graham Perkins
Delphi and Clarion for Windows
Clarion for Windows version 1.5 and Delphi Desktop Edition version 1 with focus on database application development. From Sean Gates.
The Case for Delphi
"They are concerned that by using Delphi we will not be able to integrate into new technologies like Office 2000". Read this article and you'll find out that they are wrong. From DelphiMag.com
Conclusion
It is up to you as the developer to make your own decision based on your needs, but you have to know that: "No language is perfect nor perfectly suited for every programming purpose" If you already know what tool is best for you than you should know: "Better to suffer, while limitations are sufferable, than to abandon the languages to which we are accustomed."
Lets the Game Begin
My First Delphi Program
The first step in developing a Delphi application is to plan what the user will see. We have to design the screens. What menus do you want? How many windows should there be? Will the application have places to enter text (edit boxes)?
In Delphi, the objects a programmer places on the windows (forms) are called components. Some of the components are buttons, edit boxes, labels, combo boxes, option buttons, etc.
As you will see, all these components (objects) are standard Windows objects. Depending on which version of Delphi you have, you start with more than 100 components at your disposal, and than you can add components by buying them or creating them.
Only after you design the interface of your application, you should start writing code.
Further steps in developing a Delphi application:
Customize the windows that user sees. This means placing components on the form - you literally draw the user interface, almost as though you are using a paint program
Decide what events the components on the form should recognize. For example: we have to specify what will happen if user clicks the button. An event is something that occurs as a result of a component's interaction with the user or with Windows.
Write the event procedures for those events. The programming code in Delphi that tells your program how to respond to events like mouse clicks is inside what Delphi calls event procedures.
Now lets come to Code
We'll begin by launching Delphi. When you first start the program, you are presented with both a blank form and the IDE (integrated development environment).
At the top of the blank form is the title bar with its caption. To the left of the form, the Object Inspector shows the properties for the form. Choose the caption property and change it from 'form1' to 'My first Delphi program'.
Now press F9 or choose Run-Run from the main menu. Before you even know what has happened, Delphi has built the program. The form is displayed, and the caption shows My first Delphi program. Notice that what you see is an ordinary looking Windows window. This IS a true Windows program. Window can be moved by dragging the title bar, it can be sized, it can be minimized, it can be maximized, and it can be closed by clicking the Close button.
Try it, and finally close it.
You can even locate the program in Windows Explorer (it will probably be in your \Delphi??\ directory as Project1.exe) and double-click on it to run it.
Ok, ok I know this is not something. So, let us write some code. If you still have your first program running, close it by using ALT-F4.
Click on the Events tab in the Object Inspector window. Double click in the right column of the item marked "OnClick". This brings the Code Editor window to the top of the screen. Delphi generates an event handler for the button's OnClick event. The generated code looks like this:
procedure TForm1.FormClick(Sender: TObject);
begin
|
end;
Right now, you don't need to be concerned with everything you see here. You only need to understand that the OnClick event handler is a section of code that will be executed every time the form is clicked.
Enter this code at the cursor:
form1.Caption:='User clicked on the form!';
This code simply assigns the value User clicked on the form to the Caption property of the form.
Now run the program (let's us term project, rather than program, to refer to the combination of programming code and user interface). Click on the form and notice that the caption changes from My first Delphi program to User clicked on the form!.
As you have noticed by now, this is not a very useful application. However, by creating it you have learnt some essential steps of creating any application in Delphi.
Ordinal Data Types
Extend Delphi's built-in types by constructing your own types.
Delphi's programming language is an example of a strongly typed language. This means that all variables must be of some type. A type is essentially a name for a kind of data. When we declare a variable we must specify its type, which determines the set of values the variable can hold and the operations that can be performed on it.
Many of Delphi's built-in data types, such as Integer or String, can be refined or combined to create new data types. In this article we'll see how to create custom ordinal data types in Delphi.
Ordinal types
The defining characteristics of ordinal data types are: they must consist of afinitive number of elements and they must be ordered in some way.
The most common examples of ordinal data types are all the Integer types as well as Char and Boolean type. More precisely, Object Pascal has twelve predefined ordinal types: Integer, Short int, Small int, Long int, Byte, Word, Cardinal, Boolean, Byte Bool, Word Bool, Long Bool, and Char. There are also two other classes of user-defined ordinal types: enumerated types and sub range types.
In any ordinal types, it must make sense to move backward or forward to the next element. For example, real types are not ordinal because moving backward or forward doesn't make sense: the question "What is the next real after 2.5?" is meaningless.
Since, by definition, each value except the first has a unique predecessor and each value except the last has a unique successor, several predefined function are used when working with ordinal types:
Function Effect
Ord(X) Gives the index of the lement
Pred(X) Goes to the element listed before X in the type
Succ(X) Goes to the element listed after X in the type
Dec(X;n) Moves n elements back (if n is omitted moves 1 element back)
Inc(X;n) Moves n elements forward (if n is omitted moves 1 element forward)
High(X) Returns the lowest value in the range of the ordinal data type X.
Low(X) Returns the highest value in the range of the ordinal data type X.
For example, High (Byte) returns 255 because the highest value of type Byte is 255, and Succ(2) returns 3 because 3 is the successor of 2.
Note: If we try to use Succ when at the last element Delphi will generate a run-time exception if the range checking is on.
Enumerated Data Types
The easiest way to create a new example of an ordinal type is simply to list a bunch of elements in some order. The values have no inherent meaning, and their ordinality follows the sequence in which the identifiers are listed. In other words, an enumeration is a list of values.
type TWeekDays = (Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday, Sunday);
Once we define an enumerated data type, we can declare variables to be of that type:
var SomeDay : TWeekDays;
The primary purpose of an enumerated data type is to make clear what data your program will manipulate. An enumerated type is really just a shorthand way of assigning sequential values to constants. Given these declarations, Tuesday is a constant of type TWeekDays.
Delphi allows us to work with the elements in an enumerated type using an index that comes from the order that they were listed in. In the previous example: Monday in the TWeekDays type declaration has the index 0, Tuesday has the index 1, and so on. The functions listed in the table before let us, for example, use Succ(Friday) to "go to" Saturday.
Now we can try something like:
for SomeDay := Monday to Sunday do
if SomeDay = Tuesday then
ShowMessage('Tuesday it is!');
The Delphi Visual Component Library uses enumerated types in many places. For example, the position of a form is defined as follows:
TPosition = (poDesigned, poDefault, poDefaultPosOnly,
poDefaultSizeOnly, poScreenCenter);
We use Position (through the Object Inspector) to get or set the size and placement of the form.
Subrange Types
Simply put, a subrange type represents a subset of the values in another ordinal type. In general, we can define any subrange by starting with any ordinal type (including a previously defined enumerated type) and using a double dot:
type TWorkDays = Monday .. Friday;
Here TWorkDays includes the values Monday, Tuesday, Wednesday, Thursday and Friday.
Design Patterns in Delphi
Exploring design patterns in real programming, focusing on implementation issues in Delphi
"Patterns describe a problem which occurs over and over again in our environment, and then describe the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice."
Design Patterns
Patterns are devices that allow programs to share knowledge about their design. In our daily programming, we encounter many problems that have occurred, and will occur again. The question we must ask ourselves is how we are going to solve it this time.
In object-oriented programming, a pattern can contain the description of certain objects and object class to be used, along with their attributes and dependencies, and the general approach to how to solve the problem. By analogy, design patterns are to object-oriented programming what algorithms are to procedural programming. The basic elements of procedural programming (step instruction, conditionals, and branching) aren't very useful without concepts like linked list and quick sort to give them some structure.
In other words, Design Patterns provide tested and effective solutions to common problems that occur in software development.
SINGLETON
Creating a real singleton class in Delphi
A singleton is a class that supports the creation of just one object. It's like your computer -- there's just one keyboard. So if you were writing Delphi code that simulated your computer, you would want just one object instance to deal with keyboard read, write, and control activities. The article describes how to create a class that follows the singleton pattern. The class described will take care of the singleton requirements and effects itself, effectively leaving the programmer to use the class as any others.
Implementing a Singleton Pattern
Some common examples of Singletons used in the VCL are the TApplication and TScreen classes that are existent in all Delphi applications. Others include TPrinter and TClipboard. In this article, the author presents a practical use for the singleton pattern by illustrating a global user configuration object.
TEMPLATE METHOD
Frameworks with the Template Method Pattern
The Template Method pattern are like abstract classes in the VCL. In this article, the author will create a simple application framework using a commonly used pattern, the Template Method. We will discuss two concepts: designing a framework around which you develop a user interface, and using patterns to accomplish this.
BUILDER
Extending Frameworks - Building Add-in Packages
In this article, two aspects of patterns are discussed: pattern classifications and how patterns are described. The Builder pattern is a useful creational technique for structuring complex objects resulting in a self-contained product.
MEDIATOR
Introduction to Process Control Frameworks
The Mediator pattern is used to "Define an object that encapsulates how a set of objects interact". In this article, the author uses use the Mediator pattern to illustrate how to solve the problem of process flow control in a batch processing system.
RECYCLING FACTORY
A Recycling Factory Pattern in Delphi
The problems of using and reusing many varying size objects in an application can cause fragmentation of the heap that can slow down processing speed. In this article, the author uses a factory object to make and recycle objects with minimal fragmentation effects.
DLL in Dephi
A Dynamic Link library, or DLL, is a collection of routines (small programs) that can be called by applications and by other DLLs. Like units, DLLs contain sharable code or resources, they provide the ability for multiple applications to share a single copy of a routine they have in common. The concept of DLLs is the core of the Windows architectural design, and for the most part Windows is simply a collection of DLLs.
If you look in the project file of any Delphi application, you'll see that it starts with the reserved word Program. By contrast, DLLs always begin with the reserved word Library. This is then followed by a uses clause for any needed units. In this simple example, there then follows a procedure called DllMessage which does nothing except showing a simple message.
At the end of the source code we find an exports statement. This lists the routines that are actually exported from the DLL in a way that they can be called by another application
.
VARIABLE SCOPE
Scope of Variables and Constants
The term scope refers to the availability of a variable or constant declared (or used) in one part of a program to other parts of a program.
Unless we specify otherwise, changing the value of a variable named, let's say, SomeNumber in one procedure (function) will not affect another variable with the same name in another procedure (function).
Since Delphi requires us to declare variables, it's a lot harder to fall into the trap caused by side effects accidentally. As we know by now, every variable used in some procedure has to be declared in the var section of the event handler.
In general, we declare a variable where we want to use it. For example, if we want to use a variable in an event handler, we declare the variable within the event handler.
Local Scope (+ variable declaration and initialization)
Most variables have local scope, which means that the variable is visible only within the code block in which it is declared (usually: Event Handler for some method). In particular, an event handler will not normally have access to the value of a variable in another event handler.
If we want to be sure a variable is local within an event handler, we have to declare it in the var section inside the event handler. Since we must declare a variable before we can use it, if we can use a variable without declaring it locally, we know that there is a variable with greater scope with the same name somewhere around project.
Let us look at the first example:
1. Start Delphi, this will give us (by default) new application with one blank form.
2. Double click somewhere on the form (to create OnCreate event handler)
3. Write down this code:
procedure TForm1.FormCreate(Sender: TObject);
begin
ShowMessage(FloatToStr(SomeNumber));
end;
4. If you try to run your project now, you will be prompted with: "Undeclared Identifier: 'SomeNumber'" error. This means that we haven't declared SomeNumber variable in our project (note: entire project, not FormCreate event handler).
5. To declare SomeNumber variable as double type change your code to:
procedure TForm1.FormCreate(Sender: TObject);
var SomeNumber: double;
begin
ShowMessage(FloatToStr(SomeNumber));
end;
6. Run your project, message box will appear with some strange (value of the memory region where variable is stored) number. Delphi will also give us "Variable 'SomeNumber' might not have been initialized" warning. This means that, before using declared variable, it is a good practice to initialize it (just to be sure). For that purpose add this line of code before ShowMessage...
SomeNumber := 123.45;
7. Now, when you run your project message box will display 123,45 (no errors, no warnings). Finally, we can see why local variables are called local.
8.Add one TButton component to form and double-click it to create Buttons OnClick event handler. Add the following code (so that OnClick looks like):
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(FloatToStr(SomeNumber));
end;
Again we have "Undeclared Identifier: 'SomeNumber'" error. This is what local variables are all about: even if we have declared (and initialized) SomeNumber variable in OnCreate event handler of the form, SomeNumber is not accessible in the OnClick handler of TButtton. We simply cannot use SomeNumber (with 123.45 value) in the OnClick (at least for now). This means that SomeNumber from OnCreate and SomeNumber from OnClick are two different variables (that can, of course, hold different values)
9. Don't close this project, jet. We will need it again...
10. Add the following line before ShowMessage in the OnClick event handler (we will need it later, don't worry about this for now)
SomeNumber:=555.55;
Sharing variables across procedures (event handlers)
Occasionally we will want to share the values of variables (and constants) across event handlers or across units. For example, if an application is designed to perform a calculation involving one SomeNumber at a time, that SomeNumber should be available to all procedures in a unit.
Depending on where we declare a variable, the variable can be thought of as a true global variable accessible by any other code in the application, or a unit-level variable accessible by any code in the unit.
Unit level variables - unit level scope
We put the declaration statements for unit-level variables in a var section in the unit's implementation section. Unit-level constants are declared in a const section.
Let's look at the second example:
0. We will be modifying our first example (be sure to have it)
1. Add declaration of SomeNumber, so that implementation code of the unit looks like:
...
implementation
{$R *.DFM}
var
SomeNumber: Double;
...
2. Run your program. As you can see, we don't have "Undeclared Identifier: 'SomeNumber'" error in OnClick handler of the TButton. When program starts message box will appear with 123.45 value. When you click on the Button1 message box will display 555.55; that's why we need step 10 in the first example - we have initialized SomeNumber to 555.55 in the OnClick event of the Button1.
No we have two SomeNumber variables in our project and they both hold different values.
Obviously, we have to be careful when assigning values to unit-level variables. Although we can use the same variable (or constant) name for both local and unit-level variables, this is not a good idea. Any var (or const) declaration contained in a procedure takes precedence over global (unit-level) declarations. Duplicating the names makes the global variable invisible to the procedure (Delphi doesn't tell us whether a global variable has been defined with the same name as a local variable). That is why SomeNumber holds the 123,45 value in the OnCreate event handler of the form (we cannot use global variable SomeNumber in the OnCreate procedure)
Note 1: If you really have to use two variables with the same SomeNumber name (one global and one local), you can access the global SomeNumber variable value in the forms OnCreate procedure with the call to unit1. SomeNumber (unit1 is the name of the unit with the global SomeNumber variable). That is, something like
unit1.SomeNumber:=444.44;
will change value of the global variable SomeNumber inside OnCreate event handler of the form (remember that there is a SomeNumber variable local to this procedure which will stay unchanged)
Note 2: As global SomeNumber is global to the unit we can access (more important: change) its value from any other procedure inside this unit. However click to Button 1 will reset SomeNumber value to 555.55. Better way to initialize global variables is inside initialization section of the unit.
Global variables - program level scope
If we want to create true global variables (or/and constants) in a project, we have to place the declaration in the interface section of the unit. Variables declared in the interface section will be visible (accessible) to any unit which uses that unit.
For example, to change SomeNumber variable value that is declared in Unit1 from Unit2, use this statement:
Unit1.SomeNumber:=999.99;
.
WORKING WITH COMPONENTS
An introduction to Delphi VCL and a simple application.
As you probably know by now, components are essential elements of the Delphi environment. It's crucial for every Delphi beginner to understand what VCL has to offer.
Prior to understanding this article it will be good idea to read What is Delphi, and Delphi for Beginners: Getting started.
Overview
First of all, let's distinguish components from controls. Simply putt controls are those components that the user can see. Furthermore, Delphi distinguishes between windowed and nonwindowed (graphical) controls. The major distinction is that windowed controls can receive the focus and nonwindowed controls cannot.
The distinction between windowed and graphical controls can be important when you design your user interfaces. For example, if you create a tool bar that contains a large number of buttons, you could choose a nonwindowed speed-button component instead standard Windows button components. Non graphical controls consume fewer system resources.
Some components are visual components; others are nonvisual components. A visual component, is one that can be seen by the user at run time. Visual components include components such as edit controls, buttons, list boxes, labels, and so on. A nonvisual component is one that cannot be seen by the user at run time (system timers, database components, image lists, etc.) When you place a nonvisual component on a form, Delphi displays an icon representing the component on the form. This icon is used to access the component at design time in order to change the component's properties, but the icon does not show up when the program runs.
Depending on which version of Delphi you have, you start with more than 100 components. Each page tab in the Component palette displays a group of icons representing the components you can use to design your application interface.
Each component has a set of properties - such as color, size, position, caption - that can be modified in the Delphi IDE or in your code, and a collection of events - such as a mouse click, keypress, or component activation - for which you can specify some additional behavior (in event procedures).
Adding components to the form
To place a component on the form, click once on the desired component on the toolbar. Then move the mouse cursor over to the Form and click on the Form where you want the component to be. Repeat the same procedure with the rest of the components you wish to use.
Of course, you may want a component to be smaller or larger than the default size. To change the dimensions of the component simply stretch it using the mouse (in a way you deform any standard window). Take a moment to see that Height and Width property of that controls changes in the Object Inspector.
To move a component to a different location simply select a component (click on it) and drag it to its new location. Again, you are changing properties: Left, Top.
If you would like to cancel a design-time drag operation you've already begun, do the following: after you've begun the drag but before you release the mouse button, press the Esc key. The control will snap back to its original position!
Container components
Besides the form itself, Delphi provides several components-such as the group box, panel and page control that can contain other components. The idea of a container is that all the components will behave as one at design time. For example when you move a container component, the child components move with it. Once you have placed container component on the form, make sure that it is selected than add child components to the container as you normally would.
Simple application - My Second Delphi Program
This simple application will show you how to change some of the standard component properties at design and run-time.
When you change a component's properties through the Object Inspector and Form Designer, you are said to make a design-time change. When you modify a property through code that executes when the program runs, you are said to make a runtime change.
We will build our application in few steps, so here they are: 0. Start Delphi, and as we know, you are presented with both a blank form and the IDE.
1. Put one Label (TLabel is a nonwindowed control that displays text on a form.), Edit (TEdit is a standard Windows edit control) and a Button on the form -all components are on the Standard Page of components palette
2. Change form caption to 'My Second Delphi Program', Button caption to 'Copy text'. (this is not necessary for application - we are just design-time changing properties)
The idea is to change the text in Label component to the text in Edit component when the user clicks on the Button component.
3. Select the Button and click on the Events tab in the Object Inspector window. Double click in the right column of the item marked "OnClick".
4. Enter this code (marked red).
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption:=Edit1.Text;
end;
5. Now, run the project (F9), and notice that every time you click on the button, text in Label component changes to the text in Edit box. Of course, try to change the text in Edit box before clicking on the Button to see the results.
In that line of code, that we had to write down, is everything we need to accomplish desired task. We are run-time changing the Caption property of the Label so that it's the same as the Text property of the EditBox.
When you assign a value to a property, the value on the right side of the assignment statement is assigned to the property on the left side of the assignment statement. When a value is assigned, a copy of the value is placed into the property.
Loops in Delphi
Loops
The loop is a common element in all programming languages. Object Pascal has three control structures that execute blocks of code repeatedly: for, repeat-until and while-do.
The FOR loop
Suppose we need to repeat an operation a fixed number of times.
// show 1,2,3,4,5 message boxes
var i: integer;
begin
for i := 1 to 5 do
begin
ShowMessage('Box: '+IntToStr(i));
end;
end;
The value of a control variable (i), which is really just a counter, determines how many times a for statement runs. The keyword for sets up a counter. In the preceding example, the starting value for the counter is set to 1. The ending value is set to 5.
When the for statement begins running the counter variable is set to the starting value. Delphi than checks whether the value for the counter is less than the ending value. If the value is greater, nothing is done (program execution jumps to the line of code immediately following the for loop code block). If the starting value is less than the ending value, the body of the loop is executed (here: the message box is displayed). Finally, Delphi adds 1 to the counter and starts the process again.
Sometimes it is necessary to count backward. The downto keyword specifies that the value of a counter should be decremented by one each time the loop executes (it is not possible to specify an increment / decrement different than one). An example of a for loop that counts backward.
var i: integer;
begin
for i := 5 downto 1 do
begin
ShowMessage('T minus ' + IntToStr(i) + 'seconds');
end;
ShowMessage('For sequence executed!');
end;
It's important that you never change the value of the control variable in the middle of the loop. Doing so will cause errors.
Nested FOR loops
Writing a for loop within another for loop (nesting loops) is very useful when you want to fill / display data in a table or a grid.
var i,j: integer;
begin
//be aware:
//this double loop is executed 4x4=16 times
for i:= 1 to 4 do
for j:= 4 downto 1 do
ShowMessage('Box: '+
IntToStr(i)+ ',' +
IntToStr(j));
end;
The rule for nesting for-next loops is simple: the inner loop (j counter) must be completed before the next statement for the outer loop is encountered (i counter). We can have triply or quadruply nested loops, or even more.
Note: Generally, the begin and end keywords are not strictly required, as you can see. If begin and end are not used, the statement immediately following the for statement is considered the body of the loop.
The WHILE and REPEAT loops
Sometimes we won't know exactly how many times a loop should cycle. What if we want to repeat an operation until we reach a specific goal?
The most important difference between the while-do loop and the repeat-until loop is that the code of the repeat statement is always executed at least once.
The general pattern when we write a repeat (and while) type of loop in Delphi is as follows:
repeat
begin
statements;
end;
until condition = true
while condition = true do
begin
statements;
end;
Here goes the code to show 5 successive message boxes using repeat-until.
var i: integer;
begin
i:=0;
repeat
begin
i:=i+1;
ShowMessage('Box:'+IntToStr(i));
end;
until i>5;
end;
As we can see, the repeat statement evaluates a condition at the end of the loop (therefore repeat loop is executed for sure at least once).
The while statement, on the other hand, evaluates a condition at the beginning of the loop. Since the test is being done at the top, we will usually need to make sure that the condition makes sense before the loop is processed, if this is not true the compiler may decide to remove the loop from the code.
var i: integer;
begin
i:=0;
while i<5 do
begin
i:=i+1;
ShowMessage('Box:'+IntToStr(i));
end;
end;
Break and Continue
The Break and Continue procedures can be used to control the flow of repetitive statements: The Break procedure causes the flow of control to exit a for, while, or repeat statement and continue at the next statement following the loop statement. Continue allows the flow of control to proceed to the next iteration of repeating operation. See how they work.
Delphi Tutorial [x1]
Arhiva forumului
Moderatori: Moderator Global, Administrator
Mergi la
- »[TryAgain.Ro] Bun venit!
- ↳ Inregistreaza-te!
- ↳ Logheaza-te!
- »[TryAgain.Ro] Administrare
- ↳ Prezinta-te!
- ↳ Cereri DNS
- ↳ Staff TryAgain.Ro
- ↳ Anunturi administrative
- ↳ Cerere Grade pe Forum
- ↳ Plangeri
- ↳ Dezvoltare
- ↳ Cereri Parteneriat
- ↳ Sugestii / Pareri
- ↳ Asistenta Tehnica
- »[TryAgain.Ro] Servere CS 1.6
- ↳ Gg.TryAgain.Ro
- ↳ Regulament
- ↳ Anunturi
- ↳ Cereri Admin
- ↳ Cereri Upgrade
- ↳ Reclamatii
- ↳ Cereri Unban/Ban
- ↳ Discutii
- »[TryAgain.Ro] Gaming Area
- ↳ Counter-Strike 1.6
- ↳ Addons-uri
- ↳ Harti
- ↳ Cfgs
- ↳ Tutoriale
- ↳ Pluginuri AmxModX
- ↳ Counter Strike:Global Offensive
- ↳ Tutoriale
- ↳ News
- ↳ Updates
- ↳ Resurse
- ↳ Discutii
- ↳ Other Games
- ↳ Metin2
- ↳ Minecraft
- ↳ Euro Truck Simulator 2
- ↳ GTA San Andreas
- ↳ Browser Based Games
- ↳ »[TryAgain.Ro] Design
- ↳ League of Legends
- ↳ Noutati
- ↳ Discutii despre joc
- ↳ Probleme cu jocul
- ↳ Ghiduri si Strategii
- ↳ Meciuri si tutoriale LOL
- ↳ PhotoShop
- ↳ Tutoriale Photoshop
- ↳ Resurse
- ↳ Creatii
- ↳ Cereri
- ↳ Cadouri
- ↳ »[TryAgain.Ro] Tehnologie
- ↳ Provocari
- ↳ IT
- ↳ Discutii
- ↳ Hardware
- ↳ Software
- ↳ Telefonie
- ↳ Games Zone
- ↳ Apps
- ↳ Windows
- ↳ Linux
- ↳ Mac
- ↳ Tutoriale IT
- ↳ Developement
- ↳ Web, download , tutoriale
- ↳ Theme / Templateuri
- ↳ phpBB3
- ↳ vBulletin
- ↳ MyBB
- ↳ IPB 3.x
- ↳ Tutoriale
- ↳ Index / Intro
- ↳ Scripting
- »[TryAgain.Ro] FreeTime
- ↳ Discutii Libere
- ↳ Amuzament
- ↳ Aniversari
- ↳ Intreaba-ma orice !
- ↳ Joculete
- ↳ Sport
- ↳ Filme
- ↳ Muzica
- ↳ Playlists
- ↳ Arhiva forum
- ↳ Diverse
- ↳ Discutii generale
- »[TryAgain.Ro] Arhiva