What is programming logic?
Programming in Smart Mobile Studio 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.
In the above example, we might well use the If statement to check for the Enter key.
IF THEN ELSE
Here is an example that calculates the square of 17 and see how the if statement works:
procedure TForm1.W3Button1Click(Sender: TObject);
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
W3EditBox1.Text := text;
end;
|
obs: sqr 17 = 289
We are going to see the following result on a EditBox: 17 squared <= 400
There are a number of things to note about the if statement.
First: remember that Pas2JS 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.
Using the expression A>B ? true : false
the if-then-else can also be used as an expression. In the example
var a, i : Integer;
begin
for i:=0 to 1 do begin
a := if i > 0 then 42 else 7;
WriteLn(a);
end;
|
'a' will be set to 42 in case 'i' is greater than zero. Otherwise it is set to 7.
var a$55 = 0;
var i$3 = 0;
for(i$3=0;i$3<=1;i$3++) {
a$55 = (i$3>0)?42:7;
WriteLn(a$55);
}
|
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:
procedure TForm1.W3Button1Click(Sender: TObject);
var
number: Float;
text: string;
begin
number := Sqrt(10);
if (number > 1) and (number < 3) // Both conditions must be satisfied
{//if (condition1) And (condition2)} then
begin
W3EditBox1.Text := '3 < number > 1';
ShowMessage(FloatToStr(number));
// statement1;
// statement2;
end // Notice no terminating ';' - still part of 'if'
else
begin
W3EditBox1.Text := 'number > 3';
ShowMessage(FloatToStr(number));
// statement3;
// statement4;
end;
end;
|
obs: number = 3.1622
We are going to see the following result on a EditBox: number > 3
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.
function W3Button1Click(Self, Sender$5) {
var number = 0;
var text = "";
number = 3.16227766016838;
if ((number>1)&&(number<3)) {
TW3EditBox.setText($Check($Check(Self,"").W3EditBox1,""),"3 < number > 1");
alert((number).toString());
} else {
TW3EditBox.setText($Check($Check(Self,"").W3EditBox1,""),"number > 3");
alert((number).toString());
}
}
|
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.
LOGICAL 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:
procedure TForm1.W3Button1Click(Sender: TObject);
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;
|
The result is:
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.
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
I would like to Generate a random number from 15 to 20. Pas2JS don't have a built-in function called RandomRange, but you can implemented it.
function RandomRange(const AFrom, ATo: Integer): Integer;
begin
if AFrom > ATo then
Result := RandomInt(AFrom - ATo) + ATo
else
Result := RandomInt(ATo - AFrom) + AFrom;
end;
procedure TForm1.W3Button1Click(Sender: TObject);
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;
|
Result is: 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 ELSE 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:
procedure TForm1.W3Button1Click(Sender: TObject);
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
ShowMessage (Format('Unexpected number : %d',[i]) );
end;
end;
|
Tip: In Delphi you should use ShowMessageFmt('Unexpected number : %d',[i]);
In Pas2JS, ShowMessage(Format('Unexpected number : %d',[i]));
Result is: 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
procedure TForm1.W3Button1Click(Sender: TObject);
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;
|
Result is: We have a Rover car
// TCar enumeration
var TCar = [ "Nissan", "Ford", "Rover", "Jaguar" ];
function W3Button1Click(Self, Sender$5) {
var car = 0;
car = 2;
switch (car) {
case 0 :
alert("We have a Nissan car");
break;
case 1 :
alert("We have a Ford car");
break;
case 2 :
alert("We have a Rover car");
break;
case 3 :
alert("We have a Jaguar car");
break;
}
}
|
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.
|