Sunday, June 12, 2011
4 Function And Procedure
Function And Procedure is a routine that usually used to perform certain tasks or / and to place particular value.
usually when we build a program ( just open and klik form create) in fact we have created procedure thats related with even, example procedure to control program if we klik certain button. this kind of procedure identified by programmer. besides we can create function and procedure, Delphi also provides procedures and functions that are ready to use.
3.10 try..Finally
try..finally similar with try..except. just different in writting and try..finally will execute the list of statements , whether there are errors or not.
sintax :
<code>
try
<listofstatements1>;
finally
<listofstatements1>;
end;
</code>
examples try..finally
<code>
Reset(F);
try
...//proces file F
finally
CloseFile(F);
end;
</code>
3.9 Try..except
Try..Except used if there have possibility ERROR.
Sintax :
<code>
try
<statements_list1>;
except
<statements_list2>;
end;
</code>
operation: the first program will execute one or more statements under try. if not error, program will execute statements until <strong>end;</strong> statements. if any error under <strong>try</strong> statement program will jump and execute the statement below <strong>except</strong>.
attention ! try..except will work if option <strong>stop</strong> on <strong>Delphi Exception</strong> listed on page language exceptions in the menu tools-->debugger Options is not check.
examples 1 try..except
<code>
try
x:=i/j;
except
on EZeroDivide do HandleZeroDivide;
end;
</code>
<hr/>
examples 2 try..except
<hr/>
<code>
try
. . .
except
on EzeroDivide do HandleZeroDivide;
on EOverflow do HandleOverflow;
onEMathError do HAndleMathError;
end;
</code>
<hr/>
examples 3 try..except
<hr/>
<code>
try
. . .
except
on EzeroDivide do HandleZeroDivide;
on EOverflow do HandleOverflow;
onEMathError do HAndleMathError;
else
HandleAllOthers;
end;
</code>
3.8 Exit statements
The Exit statements abruptly terminates the current function or procedure.
If exiting a function, then Result contains the last set value.
Warning : use with caution - jumping is a concept at odds with structured coding - it makes code maintenance difficult.
examples :
var
name1, name2 : string;
begin
Result := 'Tanjung Kona';
repeat
if not InputQuery('Test program', 'First name :', name1)
then Exit;
if not InputQuery('Test program', 'Second name :', name2)
then Exit;
until (name <> '') or (name2 <> '');Result := name1 + ' ' + name2;
end;
3.7 Break and Continue statements
Break
The Break procedure forces a jump out of the setof statements within a loop. Like the Goto statement, it should be used with caution.
The next statement that is executed is the one following the loop terminator. For example:
for i := 1 to 10 do
begin
...
break;
...
end;
size := 10; // breaks to here
It is important to note that the Break statement only jumps out of the current loop - not out of any nested loops above it. The Goto statement can.
Continue
Passes control to the next iteration of the enclosing iteration statement in which it appears.
The enclosing iteration assumes for, while, or repeat statements.
examples :
for i = 0 to 100 do
begin
if i MOD 2 = 0 then
Continue;
end;
3.6 Go to
A Goto statement transfers program execution to the statement marked by the specified label.
Read this again! Goto does not "ask questions", it simply forces a jump to some other location in the code block. When badly used Goto could transform your code into a non-readable piece of junk.
According to the "Are you using the Goto statement in Delphi" poll, it seems 40% of Delphi developers do not even know Goto exists in Delphi. Another 40% would have a very low opinion on you if they would see Goto in your Delphi code.
Be it bad or good, Goto is in Delphi and you might need to use it, or at least need to understand how it works.
Here's a code block that might produce some very nasty, unpredictable effects:
var
label : skipOut;
label : breakCodeFlow;
j,k : integer;
begin
breakCodeFlow:
for j := 0 to 10 do
begin
for k := 0 to 10 do
begin
if Something_Related_To_J_and_K then
begin
GOTO skipOut;
end;
end;
end;
skipOut:
//continue program execution here...
if j = 0 then
begin
//some code block
GOTO breakCodeFlow;
end;
A goto statement needs a label ("skipOut" and "breakCodeFlow") to be defined in the var section.
Luckily, even though Goto can be used for bad ideas, there are some restrictions in using Goto:
* You can "Goto" only inside the same scope block.
* You cannot "Goto" out of a function of procedure.
* You cannot jump into or out of a try/finally or try/except block.
Note that if you need, for example, to skip out of a "for loop" you should be using the Break statement.
(http://delphi.about.com)
3.5 Case
Although, we can use the if statement for very complex (nested) condition testing, the case statement is usually easier to read (debug!) and the code runs more quickly.
The case statement makes it clear that a program has reached a point with many branches; multiple if-then statements do not.
Sintax :
Case <parameters> of
<number_1>:<execute_1>
. . .
. . .
. . .
<number_n>:<execute_n>
else < execute_n+1 >;examples :
begin
case days of
1 : 'Monday';
2 : 'Tuesday';
3 : 'Wednesday';
4 : 'Thursday';
5 : 'Friday';
6 : 'Saturday';
7 : 'Sunday';
end;
end;
What follows the case keyword is usually called the selector. The selector is a variable or expression taken from either the char type or any integer type (an ordinal type). String type are invalid!. However, the StringToCaseSelect custom function enables you to use the Case statement with string type variables
As you can see, the individual case statements use a single constant, a group of constants (separated by comma), or a range of constants (double dot separated). We can even add an else keyword to take care of all the remaining cases at once.
Note 1: Only one case statement will be executed, we cannot have overlapping conditions in the case statements.
Note 2: If you want to include more than one statement in the part following the colon (:), place the begin and end keywords around the multiple statements.
examples case statements usage
3.4 conditional If...Then...Else
if..then..else used to process one statements or one block statements, depending value was tested.
sintax : 1
if<expressin> then <statements>;
or,
sintax : 2
if<expressin> then <statements1>else <statements2>;
<expressin>is logic expression. sintax 1, if will test his right <expression>. if <expression> value true, then statement or block statement in his right will be process. if <expression> value false, then statement or block statement in his right will not be process.
sintax 2 : if will test his <expression>. if <expression> value true, then statement or block statement in his right will be process. if <expression> value false, then statement or block statement in else right will be process.
as a examples :
//examples 1
<>
3.3 For..Next Loop
to perform repetitions (iterations) a statement or a block of the program several times which is determined by the value of initial and final value.
Syntax :
1
for<enumerators> := <thefirst> to <thelast> do <statements>;
or,2
for<enumerators> := <thefirst> downto <thelast> do <statements>;
<enumerators> is the variable (type ordinal), that is the variables that have a definite value if substraction or addition with one unit. example : byte, shortInt, subrange etc. <senumerators> value can changed in <statements>
if we use the first form, then looping for .. next will repeat <statement> and will stop if the <thefirst>had passed <thelast>. if you use the second form, then the looping will stop if <thefirst> value is below <thelast> value. break statement can also be used here.
examples :
//ex 1
for i := 2 to 10 do
if data[i]> max then max := data[i];
//ex 2
for i := listbox1.items.count -1 downto 0 do
listbox1.items[i] := listbox1.items[i];
//ex 3
for i := 1 to 10 do
for j := 1 to 10 do
begin
x := 0;
for k := 1 to 10 do
x :=
3.2 Repeat...Until Loop
Syntax :
repeat <statement1>; . . . <statementx>; until <expression>;or the syntax in baris
repeat
<statement1>;
. . . ;
. . . ;
<statementx>;
until <expression>;
the examples ;
repeat
k := i mode j;
i := j;
j := k;
until j = 0;
normally the looping will stop if expression value is False. but we can using break to force the program exit from looping and continuing the line below the loop
3 Control Program
Control Program used to controlling program line by line. Normally program runed sequential form first line to end line . but, with control program we can set the line will runned or not, the program will continue or repeated from particular line etc.
3.1.1 While...Do loop
While...Do The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.
The syntax of a while statement :
while<expression>do<statements>;examples
var i :integer;
begin
memo1.Clear;
i:=1;
whilei<=10 do
begin
memo1.Lines.Add(inttostr(i));
i:=i+1;
end;
end;normally, the looping will stop when <expression> value False. but we can use Break to force the program exit from looping. and proceed to the line below the loop.
examples :
//looping with one statements
while Data[I] <> x do I := I + 1; //looping with one block statements
while not Eof(InputFile) do
begin
Readln(InputFile), line);
Process(Line);
end;
//looping with one block statements
While I > 0 do
begin
if A > B then
begin
C := A + B;
D := B / A;
end
else
break
end;
I := I div 2;
end;
2.4 Operators
| Operator | Hirarchy |
|---|---|
| @,not | Highest |
| *, /, div, mod,and,shl,shr,as | second |
| +, -,or,xor | Third |
| =, <>, <,>, <=, >=,in,is | Forth |
examples:
bilangan := 0;
harga := 500;
banyak := 5;
jumlah := banyak*harga;
n:=n+1;
| operator | process | process type | result type |
|---|---|---|---|
| * | multiplication | Integer | Integer |
Real | Real | ||
| / | Division | Integer | Real |
Real | Real | ||
| Div | Division round | Integer | |
| Integer | |||
| Mod | Residual division | Integer | |
| Integer | |||
| + | Addition | Integer | Integer |
Real | Real | ||
| - | Subtraction | Integer | Integer |
Real | Real |
such as examples, view the snipped program like this :
A := 1 * 2 ; // the result is 2
A := 4 / 2 ; //the result is 2
A := 5 div 2; //the result is 2, rounded down
A := 5 mod 2 ; //the result is 1, rounded up
A := 1 + 2 ; //the result is 2
A := 4 - 2 ; //the result is 2
A := 2;
B := 3;
C := exp (B*ln(A); // C= 9
D := exp (B*ln(5); //D=125
| Operators | Description |
|---|---|
| = | equals to |
| <> | not equals to |
| < | less than |
| > | greater than |
| <= | less than or equals to |
| >= | greater than or equals to |
A := 2 > 3; //false
A := 2 + 2 > 3; //true
A := 3 > 2 + 2; //false
A := 3 >= 3; //true
| operators | |
|---|---|
| Not | No |
| And | and |
| Or | or |
| Xor | Exclusive or |
view a table of logic operator Not
| Expression | Value |
|---|---|
| Not True | False |
| Not False | True |
| Expression | Value |
|---|---|
| False And False | False |
| False And True | False |
| True And False | False |
| True And True | True |
| Expression | Value |
|---|---|
| False And False | False |
| False And True | True |
| True And False | True |
| True And True | False |
2.3 variables
variable is a place in the computer memory that is named (as an identifier) and allocated to accommodate data. the difference between variable and const are :
- const used when compiling program, and variables it is used when the program RUN
- const can not change when program run, and variables can changed while program run.
each variable have a name called identifier. it recommended when you making variable name you must accordance with the data contain and easy to remember.
some rules that apply when making a variable :
- must start with character( letter) or underscore
- unique(not same with other variables)in same scope
- note the length character , just 63 character can be read as variable (64 character thereafter will be ignored)
- some characters that should not be used : operator(+, -, *, /, <, >,:, ;, , , etc)
2.3.2 variables scope
Variables scope is area variable used.usually associated with age (life time) variable. several variables are known throughout the program and used while the program run. some variable known in procedure and function and it just used when the procedure and function start.
generally, a variable will be recognized in the scope where variable declared. as samples : if you declaring variable on function, then the scope of variable just start begin declaration line untill end of funtion. including the function or procedure called by the function. whereas if variable declared on interface in the unit, then the scopes of variable start from declaration line untill end of unit. including other unit called by the unit.
global variable is a larges variable scope.
local variableis a smallest variable scope.
unit Unit1;
interface
uses
windows, Message, SysUtils, Classes, Gaphics, Controls,
Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(sender : TObject);
procedure FormClick(sender : TObject);
private
{private declarations}
public
{public declarations}
end;
var
Form1 : TForm;
A : Single;
implemetation
{SR *.DFM}
procedure FormCreate(sender : TObject);
begin
A:=5; //this is global varaible
end;
procedure FormClick(sender : TObject);
var A: single
begin
A:=10;//this is local variable;
end;
end.
2.2 Const
Const is fixed value, examples : 1 ,A, Tanjungkona etc. we can use one names to represent a const.
view example program :
begin
. . .
. . .
totdiscount:=tot*0.30;
totdiscountplus:=tot*0.35;
snipped program above, we can write like is:
const
discount =0.30;
discountplus=0.35;
begin
. . .
. . .
totdiscount:=tot*discount;
totdiscountplus := tot*discountplus;
why we use const :
- programs easier to read
- to avoid wrong typing
- we can use a single const repetitive, so if there any change in const, we just change it in declarations.
2.Data Type, Variables and Operators
2.1 Data Type
2.2 Constans
2.3 Variabels
2.4 Operators
2.1 Data Type
Borland offers several types of data. we have to learn it, so it can be used properly and efficiently.there are several considerations to determine the Data type that we will use in the program.
- memory usage and data ranges
there are differences in the allocation of memory for one type of data with other data types. The best course uses data types according to our needs. example if we procces the data having ranges (0-100 )without decimals, then we used data type : Byte.(it is needed 1 Byte), compared if we use data type : word (2 byte ) or Integer (4 byte).but of course, if we processing the data over data type Byte( >100). we must not use data type :Byte.
- accuracy of calculation
although the memory savings is needed but we must having accuracy in calculation.so we must use the data type that having accuration in calculate.
there are data Type used in Borland- 2.1.1 Integer Integer used to specify the number with no decimal. there are integer tipe with range in memory used
- 2.1.2 Used to declaretype of data that contains decimals
- 2.1.3 Boolean it is used to declare logic data, thats TRUE and FALSE borland delphi have 4 boolean type :
- 2.1.4 Character used to declare character 1 letter.borland have 3 Character Type:
- 2.1.5 String Used to declare more character example ; name, adress, code etc. borland have 3 string type:
- 2.1.6 Array Array is a single variable that can be used to store a set of similar data. to make differrent path array using element number in the right of array name : view the example:
- 2.1.7 Record
- 2.1.8 Enumeration and SubRange type expressed sequence data with similar type. enumerate declarations exampes :
| Tipe | Ranges | Byte |
| Byte | 0-255 | 1 |
| Word | 0-65535 | 2 |
| ShortInt | -128-127 | 1 |
| SmallInt | -32768 - 32767 | 2 |
| Integer | -2147483648 - 147483647 | 4 |
| Cardinal | 0 - 2147483648 | 4 |
| LongInt | 2147483648 - 147483647 | 4 |
| Type | Ranges | Byte |
| Real48 | 2.9 x 10-39 s.d 1.7 x 1038 | 6 |
| Single | 1.5 x 10-45 s.d 3.4 x 1038 | 4 |
| Double | 5.0 x 10-324 s.d 1.7 x 10308 | 8 |
| Extended | 3.6 x 10-4951 s.d 1.1 x 104932 | 10 |
| Comp | -263+1 s.d 263-1 | 8 |
| Currency | -922337203685477.5808 s.d 922337203685477.5807 | 8 |
| Type | Byte |
| Boolean | 1 |
| ByteBool | 1 |
| WordBool | 2 |
| LongBool | 4 |
| Type | Byte | Fields |
| Char | 1 | 1 ANSI Character |
| AnsiChar | 1 | 1 ANSI Character |
| WideChar | 2 | 1 Unicode Character |
| Type | Byte | Max Fields |
| ShortString | 2 s.d 256 | 256 Character |
| AnsiString | 4 s.d 2 GB | 231Character |
| WideString | 4 s.d 2 GB | 230 Character |
var day:array[1..7] of AnsiString;
begin
day[1]:='Sunday';
day[2]:='Monday';
. . .
. . .
edit1.text:=day[1];
record data type used to store a set of data that may be different types, but interrelated. sample data using record Type ex: to save item data that contains; item code, item name and unit price. note the following program snippet :
type
recitem=record
code : String[6];
name : String [30];
Unitprice : Single;
end;
var
itemm : recitem;
begin
itemm.code :='ns.001';
itemm.name :='naruto sipudden';
itemm.unitprice :=15000;
type>
color = (red, blue, green, yellow, orange, black, white );
var
paintcolor : color;
subrange declaration examples
type
mycolor = blue..orange;
uppercase='A'..'Z';
value =0..100;
var
paintcolor=mycolor;
testscores=value;
finalvalue=uppercase;
1.4 delphi component
After the first attempts to create a simple application program.you may know more about Delphi and feel how easy it is Delphi and sophisticated in making the application program. to be able to master it , of course we must to learn the basics by studying the terms and delphi component it was used to create program.
- Project
- Form
- Unit
- Program
- Properties
- Event
1.3 general steps to create applications
- 1.3.1 create the first application
- 1.3.2 save applications
- 1.3.3 run and stop applications
- 1.3.4 close applications
- pictures of objects and layout of the window form using the icons of objects in the component palette.
- if necessary, determine the properties of each component using the properties of the object inspector, sometimes the programmers prefer to determine the object's properties through code in the form create.
- write code for events on the desired object. event is an event perceived object, such as point, click, or other events
1.2 start delphi
Now we start making aplication with delphi so you can know and feel the ability of Borland Delphi, we will soon discuss and try to use it. we will limit and avoid the first detailed and technical discussion, so you get a general picture of sophistication and ease of use Borland Delphi
to start delphi follow these steps
- click start icon on the start programs ->borland delphi -->delphi
- now you see the delphi form(delphi IDE )
continue reading>>> 1.3 general steps to create applications
1. to know and try borland delphi
- 1.1 To know Borland Delphi
- 1.2 Start Borland Delphi
- 1.3 General Steps to create applications
- 1.3.1 create the first application
- 1.3.2 save applications
- 1.3.3 run and stop applications
- 1.3.4 close applications
- 1.4 Delphi Component
Borland Delphi is a programming language that works within the scope of MS-Windows. such as MS-Visual Basic, Borland Delphi can take advantage of the ability of MS-Windows optimally. ability can be used to design an application that looks like any other application based on MS-Windows.
Kemmapuan Borland Delphi in general is to provide components that allow you to create applications that match the look and workings of MS-Windows, reinforced with structured object pascal programming language that is very famous.
specifically for the Borland Delphi programming base data object provides a powerful and complete, making it easier programmmer to create applications for database applications