Module 6. Conditional Execution in Program. IF...THEN...ELSE statement This structure is called a branching structure.
Choosing one from two or more alternatives is quite common the pro- gramming. In Delphi language, the selection is performed using an If…
Then…Else statement.
Syntax:
If <logical expression> Then <statement 1>
Else
<statement 2>;
The order of execution of If…Then…Else: First, the logical expression is evaluated,
If the logical expression evaluated to True, then statement 1 is executed, Otherwise (logical expression evaluated to False), statement 2 is execut- ed.
Example 1.
Given two integer numbers, compute the maximum value of them.
Solution:
procedure TfrmMy.btnMaxClick(Sender: TObject); var a, b, m: integer; begin a:=StrToInt(edtA.Text); b:=StrToInt(edtB.Text); if a>b then
Module 6. Conditional Execution in Program. IF...THEN...ELSE statement m:=a else m:=b; lblMax.Caption:=IntToStr(m) end;
It should be noted that the If…Then…Else statement does not need a semicolon before the Else keyword, because it is a single complex state- ment, and there cannot be Else without If.
You can use compound statements when Delphi language permits only a single action but you need to execute several actions. A compound statement consists of several statements enclosed in the operator brack- ets begin…end.
For example, if it is necessary to execute more than single statement in the Then or Else branches, then these statements are enclosed in the operator brackets begin…end:
… If x<0 Then begin y:=1; k:=k+1; end Else begin y:=2*x; k:=x; end; compound statement compound statement
Module 6. Conditional Execution in Program. IF...THEN...ELSE statement Sometimes choices are different:
This structure is represented by the shorter statement If…Then.
Syntax:
If <logical expression> Then <statement 1>;
The short version of the conditional statement gets executed just like the long version. If the logical expression evaluates to True, then statement
1 gets executed. Otherwise no statements are executed in the course of
Module 6. Conditional Execution in Program. IF...THEN...ELSE statement
Exercises
Exercise 1.
Two integers m and n are entered by the user.
If n is divisible by m, then the result of the division of m by n should be displayed. Otherwise the program should display the message “n cannot be divided by m”.
Exercise 2.
Given a three-digit integer, decide whether it is a palindrome, i. e., whether it reads the same left to right and right to left.
Exercise 3.
Find the maximum and minimum of three different real numbers.
Exercise 4.
A home contains n apartments numbered sequentially, starting with the number a. Figure out whether the sum of all apartment numbers is even or not.
Nested If…Then…Else statement.
Practicing Task Solving
Statements that follow Then and Else can be conditional statements too; in this case, the If…Then…Else statement is called a nested statement.
For example:
If <logical expression 1> Then <statement 1>
Else
If <logical expression 2> Then <statement 2>
Else
<statement 3>;
Each of the instructions (instruction 1, instruction 2, instruction 3) can be compound; i. e., in Then or Else it is possible to place more than one instruction, having bracketed them in a begin… end block.
For example:
If <logical expression 1> Then begin
<statement 1>
If <logical expression 2> Then begin
<statement 2> <statement 3> MODULE 7
Module 7. Nested If...Then...Else statement. Practicing Task Solving Else
<statement 4>; END
Else
If <logical expression 3> Then <statement 5> Else begin <statement 6>; <statement 7>; end;
Let’s examine the next fragment of code: If <logical expression 1> Then If <logical expression 2> Then <statement 1>
Else
<statement 2>;
It can seem ambiguous, since it isn’t clear to what Then Else belongs (to the first Then or to the second Then). There is a rule that Else belongs to the closest If.
To avoid confusion and possible mistakes, it is desirable to put the nested If… Then… Else inside the begin… end block.
Exercises
Exercise 1.
Find the square roots of the quadratic equation Ax2+Bx+C=0 (A≠0). If
the equation has no valid roots, display the corresponding message.
Exercise 2.
Find out if a given year is a leap year. A year is a leap year if it is divisible by 4, but among years that are also divisible by 100, leap years are only
Module 7. Nested If...Then...Else statement. Practicing Task Solving those that are divisible by 400. For example, 1700, 1800 and 1900 are not leap years, but 2000 is a leap year.
Exercise 3.
Real numbers X, Y (X≠Y) are given. Replace the smaller number with its arithmetic mean, and replace the greater number with its triple product.
Exercise 4.
Integer k (1 <= k <= 180) is given. Find what digit is in the k-position of 10111213 … 9899 sequence of all two-digit numbers in order.
Procedures
It is not sufficient to know the operators of some programming language to write programs with ease, using as little time and introducing as few errors as possible. Rather, it is necessary to become proficient with structured or procedural programming skills and principles.
The practical application of those principles allow you to: • easily write programs
• create understandable and readable programs • find program errors faster, and
• more quickly change and improve programs.
One of the main principles of structured programming is called top-
down programming. This principle states that the main task of any pro-
gram has to be split into several subtasks. Then, every subtask should be split into even more simple subtasks and this process continued until you end up with a set of small, simple tasks that are easy to implement.
Separate subtasks are called procedures in Delphi parlance.
Let us solve the task of finding quadratic equation roots. The equa- tion will be specified as three coefficients.
First we create a new form named frmQuadEq and in the Caption property we enter “Solution of quadratic equation”.
We will create the text boxes edtA, edtB and edtC for values of the corresponding variables A, B and C. We accept the Text property of these boxes for faster entry of the coefficients.
A label lblCoefs is put above those text boxes; its Caption property should contain “Enter coefficients of quadratic equation”.
Module 8. Procedures We also need labels lblX1 and lblX2 to show the values of the roots of the equation. Another label lblNo contains the text “No real roots are found” in the Caption property. We set the Visible property of these la- bels to False so that they will not be shown at the program start.
We also need a button btnFind to run the solution process. Let’s double-click and start writing code.
First we document our solution using comments. Comments in Del- phi can be placed inside curly braces or, more conveniently, after double slashes //:
//Enter quadratic equation coefficients A, B and C //Compute discriminant D
//IF D >= 0 then
//Compute equation roots X1 and X2 //display roots
//else
//Notifying user that there is no solution
This overview of the solution gives us the number of needed vari- ables, procedures, and functions. If a single line of a solution has to be expressed in several Delphi statements, then we will write a procedure; otherwise a single statement will be sufficient.
Given the above consideration, let’s rewrite the solution in Delphi: procedure TfrmQuadEq.btnFindClick(Sender: TObject); var
A, B, C, D, X1, X2: real; begin
coefInput(A, B, C); //reading of coefficients A, B, C
Module 8. Procedures begin
calc(A, B, D, X1, X2); //compute roots x1, x2 from A, B and D
prn(X1, X2); //print roots x1, x2
end
else //else
lblNo.Visible:=true; //Notifying user about ab‑ sence of solution
end;
In the body of the procedure, we see the names of the actions that the program has to execute to solve the task. Those actions are called procedures; values inside parentheses are called procedure parameters.
When Delphi encounters the name of an action that is not a keyword or statement, it assumes that it is the procedure call. It then transfers the control to the procedure with the given name (in our case, names are coefInput, calc and prn). After executing the procedure statements execution returns back into the calling routine, and the program executes the next statement after the procedure call.
Procedure call syntax:
<procedure name> (<call parameters list>);
Procedures should be defined in the Implementation section before referring to them in the call. You have to write the procedure before calling it.
Procedure definition syntax:
procedure <procedure name> (<formal parameters list>);
Module 8. Procedures begin
<statements> end;
As we see, the procedure call uses the call parameters, and the procedure definition uses formal parameters. Formal parameters list specifies types for all parameters. There is one-to-one correspondence between call parameters and formal parameters.
The number, order, and types of call and formal parameters should be identical.
Let’s define our procedures, beginning with the prn procedure.
In this procedure, the formal parameters Xf and Xs correspond to the call parameters X1 and X2. Formal parameters Xf and Xs are value parameters; they are passed from caller to Prn and are not returned back to the caller. Procedure Prn(Xf, Xs: real); begin frmQuadEq.lblX1.Visible:=true; frmQuadEq.lblX1.Caption:=’x1=’+FloatToStr(xf); frmQuadEq.lblX2.Visible:=true; frmQuadEq.lblX2.Caption:=’x2=’+FloatToStr(xs); end;
Here we make labels with the root values visible and put the answers there. We would get an error if we wrote lblX1.Visible:=true. In the user-defined procedures, we have to write the complete name of the component (specifying to which form it belongs because there can be several forms in the program, in general).
Let’s write a procedure to input coefficients. We have to take coefficients from the text boxes and put them into corresponding variables. For the values of variables to be returned from procedure to main program, we have to use variable parameters. Variable parameters not only pass data to procedures, they also put data back into the variables of the main
Module 8. Procedures
program. To define parameters as variables, we have to use the keyword
var before them. Call parameters should be variables for the procedure’s
variable parameters:
Procedure coefInput(var k1, k2, k3: real); begin
k1:=StrToFloat(frmQuadEq.edtA.Text); k2:=StrToFloat(frmQuadEq.edtB.Text); k3:=StrToFloat(frmQuadEq.edtC.Text); end;
The formal variable parameters k1, k2 and k3 correspond to the call parameters a, b and c. Please note the use of StrToFloat function. We have to use it because the Text property of a text box is of type string and our variables are type Real. We have to convert types using this function, and the use of the function also allows code completion to properly recognize your intent.
Let’s define the final procedure — how to compute the roots of equations. We have to return values of roots, so the formal parameters Xf and Xs will be variable parameters. We do not need to return first and second coefficients and discriminant values. They will be passed as value parameters.
procedure Calc(k1, k2, dis: real; var Xf, Xs: Real);
begin
Xf:=(–k2+Sqrt(dis))/(2*k1); Xs:=(–k2‑Sqrt(dis))/(2*k1); end;
After we run the program and enter the coefficients, we’ll see one or another set of labels on the form. Some labels will remain visible if we enter another set of coefficients to produce another set of labels. To get improve the behavior of the program, we’ll define another procedure that will put everything into a clean start state. This will be procedure without parameters that we’ll call it Init:
Module 8. Procedures procedure Init; begin frmQuadEq.lblX1.Visible:=false; frmQuadEq.lblX2.Visible:=false; frmQuadEq.lblNo.Visible:=false; end;
Exercises
Exercise 1.Create a program that exchanges values between variables A and
B and exchanges values of variables C and D. Define a procedure that
exchanges the values of two variables.
Exercise 2.
Given the lengths of the sides of two triangles, find the sum of their perimeters and their squares. Define a procedure to compute the perimeter and area of a triangle if you know the lengths of its sides.
Exercise 3.
Find a square of a ring with inner radius R1 and outer radius R2. Define and use this procedure to compute the area of a circle.
Exercise 4.
Functions
Now let’s examine the functions. Functions are the same as procedures except that they return a value in addition to executing statements.
Delphi has a lot of built in functions but there are many situations when you need to write your own functions. For example, we need to solve a task using the tangent function Tg(A) multiple times, but there is no such built in function. Below is a simple example:
There is a right triangle. The angle (in degrees) and the adjacent leg’s length are given. Calculate another leg.
Double-click the button to get into code editor:
procedure TfrmCatheti.btnRunClick(Sender: TObject); var
a, b.alfa: real; begin
alfa:=StrToFloat(edtAlfa.Text); //Set angle alfa
a:=StrToFloat(edtAlfa.Text); //Set adjacent leg a
b:=a*tg(alfa); //Calculate another leg b
lblB.Caption:= FloatToStr(b); //Output b
end;
We needed only to describe our function. Functions are described in the Implementation section. When you declare a function, you specify its name, the number and type of parameters it takes, and the type of its return value.