Monday, August 27, 2012

Looping

"When we find words repeated in a discourse, and, in trying to correct them, discover that they are so appropriate that we would spoil the discourse, we must leave them alone. This is the test; and our attempt is the work of envy, which is blind, and does not see that repetition is not in this place a fault; for there is no general rule."
Blaise Pascal, Pensees

Repetition involves the organisation of a block of actions that is executed a number of times according to controls. The control test can be placed at the beginning (e.g., while {condition} do {loop} ) or the end of the loop (e.g., repeat {loop} until {conditon}), or with the condition set the iteration a set number as the loop (e.g., for {loop sequence} do {code}).

Consider a simple loop which reads a series of n real numbers, and prints out the sum and average of those numbers.

program averages (input, output);
 var i, n : integer;
  sum, next, average : real;
begin
  sum := 0;
  writeln ('Enter the number of values you want summed and averaged');
  read (n);
  for i := 1 to n do
   begin
    writeln ('Enter number');
    read(next);
    sum := sum + next
   end;
  average := sum/n;
  writeln ('The total value is ', sum);
  writeln ('The average value is ', average)
end.

Another simple example of the repeat ... until sequence computes the factorial of a number of integers, usually presented as n!
program factorial (input, output);
var sum, number, finalnumber : integer;
begin
sum := 1;
number := 1;
writeln ('Enter the number you want to factorial');
read (finalnumber);
repeat
sum := sum * number;
number := number + 1
until number = finalnumber+1;
writeln ('The factorial of n! ', finalnumber, ' is ', sum)
end.

Note that in this particular case the finalnumber condition to exit the loop, is finalnumber+1, otherwise it will exit one number early. Another way to express this would be with a while .. do loop, as follows:
program factorial2 (input, output);
var sum, number, finalnumber : integer;
begin
sum := 1;
number := 1;
writeln ('Enter the number you want to factorial');
read (finalnumber);
while number < finalnumber do
begin
sum := sum * number;
number := number + 1
end;
writeln ('The factorial of n! ', finalnumber, ' is ', sum)
end.

Note that there are memory limits on what can be achieved.
lev@racoon:~/programming/pascal$ ./factorial2
Enter the number you want to factorial
20
The factorial of n! 20
is 0

(The actual answer is 2432902008176640000 - if the variables were assigned as type real, the program would work).
One of the very powerful features of loops is the capacity to create loops within loops. For example, if the sum and average loop recognised unit sales, a loop could be constructed where the number of iterations represented a number of salespeople, the number of values represented days of the week (or month, etc), and comparative averages could be calculated and compared.

Tuesday, March 22, 2011

Branching

A branching mechanism in a programming language is simply a method to make path-dependent choices. Three different branching mechanisms are introduced here; the case statement, the if-then compound statement and the if-then-else compound statement.
The case statement simply requests the program evaluates an expression according to label lists. When those labels equate with the expression then the a statement is carried out. The case statement concludes with an end.

Here's a simple example.

program LeapYear; {Decides whether an entered year might be a leap year}
var Year: integer;
procedure NonCenturyYear (Year : integer);
begin
case (Year mod 4) of
0: writeln('That year is a leap year');
3: writeln('Next year might be a leap year!');
2, 1: writeln('That is not a leap year');
end {case}
end;

procedure CenturyYear (Year : integer);
begin
if (Year mod 400) = 0
then writeln('That is a leap year')
else writeln('That is not a leap year')
end;

begin {program}
writeln('Please enter a year you wish to test');
readln(Year);
if (Year mod 100) = 0
then CenturyYear (Year)
else NonCenturyYear (Year)
end.


You will note that there are a lot of conditional statements in the text of this program. The entire point of a program is to calculate these! To improve the program we have the opportunity to combine the case branching mechanism with the if-then and if-then-else branching mechanisms.

With an if-then branching mechanism a statement is evaluated. If it is true, then a statement is followed. If the statement is false it simply carries on to the next instruction. With an if-then-else statement the same applies except there is a specific statement when the initial statement evaluates as false.

Thus the leap year program can be expanded to the following, illustrating the use of case and the if-then-else branching mechanisms.


program LeapYear; {Decides whether an entered year might be a leap year}
var Year: integer;
procedure NonCenturyYear (Year : integer);
 begin
  case (Year mod 4) of
   0: writeln('That year is a leap year');
   3: writeln('Next year might be a leap year!');
   2, 1: writeln('That is not a leap year');
  end {case}
 end;
procedure CenturyYear (Year : integer);

begin
  if (Year mod 400) = 0
  then writeln('That is a leap year')
  else writeln('That is not a leap year')
end;
begin {program}
  writeln('Please enter a year you wish to test');
  readln(Year);
  if (Year mod 100) = 0
  then CenturyYear (Year)
  else NonCenturyYear (Year)
end.


The following is the compilation and some tests.


lev@squirrel:~/programming/pascal$ fpc leap.pas
Free Pascal Compiler version 2.4.0-2 [2010/03/06] for i386
Copyright (c) 1993-2009 by Florian Klaempfl
Target OS: Linux for i386
Compiling leap.pas
Linking leap
/usr/bin/ld: warning: link.res contains output sections; did you forget -T?
23 lines compiled, 0.2 sec
lev@squirrel:~/programming/pascal$ ./leap
Please enter a year you wish to test
0
That is a leap year
lev@squirrel:~/programming/pascal$ ./leap
Please enter a year you wish to test
1000
That is not a leap year
lev@squirrel:~/programming/pascal$ ./leap
Please enter a year you wish to test
2000
That is a leap year
lev@squirrel:~/programming/pascal$ ./leap
Please enter a year you wish to test
2011
Next year might be a leap year!

Monday, March 21, 2011

Procedures and Functions


"Continuous eloquence wearies. ...Grandeur must be abandoned to be appreciated. Continuity in everything is unpleasant. ...Nature acts by progress, itus et reditus. It goes and returns, then advances further, then twice as much backwards, then more forward than ever, etc. The tide of the sea behaves in the same manner; and so apparently does the sun in its course." Blaise Pascal, Pensées (1669)

Good programming style can be assisted by writing a program in pseudo-code first, to ensure that the logic is sound, is preferable as a first stage before ensuring the syntatic rules are correct. Readability of a program is is enhanced with indentation. Finally, the task of a program is assisted by breaking large problems into smaller subtasks which are discrete and abstract from the particular task.

It is with the latter in mind that functions and procedures are introduced. Pascal includes a number of standard functions, especially for arithmetic. For example the sqrt function, for square roots takes the value of an integer or real and reveals a real value. The value of sqrt(16) is 4.0. A function consists of an argument and a returned value. In this case the argument is 16 and the value returned is 4.0. Not surprisingly arithmetic functions can be combined with larger problems.

The following represents some of the predefined Pascal functions:


FunctionDescriptionArgument TypeReturned Value
absabsolute valueinteger, realinteger
roundroundingrealinteger
trunctruncationrealinteger
sqrsquaringinteger, realinteger, real
sqrtsquare rootinteger, realreal


Further in the interest in breaking down tasks into subtasks, Pascal allows for procedures. The main body of a program makes a procedure call which invokes what is effectively a subprogram. A procedure has any number of formal parameters with their specificied type. When a procedure is called the actual variable paramters are given to the procedure and returned after calculation. The scope of a variable or constant declared in a procedure remains within that procedure and any nested procedures. A variable or constant declared within the main scope of a program is universal for that program.

The following example, based on the 628 AD solution to quatric equations by the Indian mathematician Brahmagupta, makes use of twp arithmetic functions (square and square root), a procedure allowing input of the values, and the passing of values from the main program to the Quadvalues procedure.


program Quad;
var a, b, c, x : real;
procedure Quadvalues(var x, y, z : real); {Note that the variables differ in the procedure to the main program}
begin
writeln('Please enter the values for the a, b and c for a quadratic equation');
readln(x, y, z);
end;
begin {main}
Quadvalues(a,b,c);
x := (sqrt(4*a*c+sqr(b))-b)/(2*a) ;
writeln('The quadratic solution for x with the values', a, b, c);
writeln(x);
end.


Compilation and executing the program results in the following:


lev@squirrel:~/programming/pascal$ fpc quad.pas
Free Pascal Compiler version 2.4.0-2 [2010/03/06] for i386
Copyright (c) 1993-2009 by Florian Klaempfl
Target OS: Linux for i386
Compiling quad.pas
Linking quad
/usr/bin/ld: warning: link.res contains output sections; did you forget -T?
13 lines compiled, 0.1 sec
lev@squirrel:~/programming/pascal$ ./quad
Please enter the values for the a, b and c for a quadratic equation
12 52 44
The quadratic solution for x with the values 1.20000000000000E+001 5.20000000000000E+001 4.40000000000000E+001
7.24891928816246E-001

Sunday, March 20, 2011

Basic Program Structure and Syntax

A FreePascal program has the following general form.


PROGRAM ProgramName (FileList);
TYPE { Type declarations }
type = value;
CONST { Constant declarations }
constant = value;
VAR { Variable declarations }
variable = value;
FUNCTION FunctionName;
PROCEDURE ProcedureName (parameters);
{ Functions and Procedures }
BEGIN
{ Main statements }
END.


Every program begins with a program header. The header statement must be terminated by a semi-colon. The header is followed by type definitions, constant and variable declarations. Each of these are terminated by a semi-colon. Combined, the header, type, constant and variable structures make up the Declaration body of a FreePascal program.

Functions, procedures and the Main structures make up the Program body of a FreePascal program. Functions and procedures have names in their header which is terminated by a semi-colon. The main part of the program is terminated by a full-stop.

The general form of a procedure declaration is


PROCEDURE ProcedureName (parameter declarations);
TYPE { Type declarations }
type = value;
CONST { Constant declarations }
constant = value;
VAR { Variable declarations }
variable = value;
(PROCEDURE and FUNCTION declarations)
PROCEDURE ProcedureName (parameters);
{ Functions and Procedures }
BEGIN
{ Procedure statements }
END;


In other words, a procedure is a program within a program.

Saturday, March 19, 2011

Variables and Constants, Input and Output, Data Types, Assignment Statements


The understanding and the feelings are moulded by intercourse; the understanding and feelings are corrupted by intercourse. Thus good or bad society improves or corrupts them. It is, then, all-important to know how to choose in order to improve and not to corrupt them; and we cannot make this choice, if they be not already improved and not corrupted. Thus a circle is formed, and those are fortunate who escape it. Blaise Pascal, Pensees, 1669


The reading, writing and modification of variables provides a core function of programming in a manner that is similar to the use variables in algebra. In Pascal a variable is any string of letters and numbers that begins with a letter. It is better programming practise to write a variable that has a meaningful name in context; the variable "InterestRate" makes reading a program easier than a variable named "Z". As the name indicates, variables are values whose value can be changed. In contrast, a constant is a value whose value does not change, for example the location of a configuration file. The same convention should be used when naming constants as variables, however the use of capitals is a good convention.

Variables may be of different types. The basic data types are integers (whole numbers), real numbers (fractional values), boleean values (true or false) and char (a single character), string (an array of char). Pascal uses strong types, meaning that mixing between different types is prohibited. Other programming languages use weak-typing meaning that a conversion to or from different types are required when mixed. Pascal also has static types, when means that type-checking is performed as part of compilation, rather than during execution. The alternative is dynamic typing - which surrenders safety for flexibility. When it comes to type, Pascal is strong, static and safe.

The following program illustrates the use of variables, constants and types.


program Circum;
const PI = 3.14149;
var diameter, circumference : real;
begin
Writeln('Enter the diameter of the circle');
Readln(diameter);
circumference := PI * diameter;
Writeln('The circle has a circumference of ', circumference)
end.


There are a number of things to notice about this program.

Firstly is the use of = and := for the constant 'PI' and the use of the variable 'circumference', respectively. In the first case the value of PI is equal to the value given. In the latter case, called an assignment operator, the variable on the left-hand side "becomes equal to" the value given on the right hand side.

Secondly, the constants and variables in the program are declared and the type of variables is stated.

Finally, there is basic input and output through the readln and writeln statements. Content from standard input (from keyboard to screen) is read by the program, stored as a variable, which is then used for a calculation, the result of which is sent as part of a statement to standard output (the screen).

Taken as a whole, this program covers a great deal of some basic features of a Pascal program! The program in compilation and operation can be carried out as follows.


lev@squirrel:~/programming/pascal$ fpc circum.pas
Free Pascal Compiler version 2.4.0-2 [2010/03/06] for i386
Copyright (c) 1993-2009 by Florian Klaempfl
Target OS: Linux for i386
Compiling circum.pas
Linking circum
/usr/bin/ld: warning: link.res contains output sections; did you forget -T?
10 lines compiled, 0.1 sec
lev@squirrel:~/programming/pascal$ ./circum
Enter the diameter of the circle
22
The circle has a circumference of 6.91127800000000E+001

Friday, March 18, 2011

Hello World!


Je n'ai fait celle-ci plus longue que parce que je n'ai pas eu le loisir de la faire plus courte. (I would have written a shorter letter, but I did not have the time.)
Blaise Pascal, Provincial Letters: Letter XVI


It is typical in computer programming courses to begin with the simple example of a program that prints "Hello World!". It is a good enough place to start for our purposes. You can use either the IDE or your favourite text editor for this simple program and save the file as hello.pas. It is recommended that the programs be kept in a sensible place (e.g., ~/programming/pascal) for easy and consistent access.

The following is the content of the program:


program HelloWorld;
begin
writeln('Hello World!');
end.


The first line provides a title for the program. The second is a block for the program's actions, starting with a begin statement and concluding with an end statement. The content of the block consists of a single statement, to write a line that outputs 'Hello World'. Note that the brackets for the writeln statement which enclose the text field and the semi-colon to mark the end of the statement.

At first the program is written in source code, a high-level language comprehensible to humans. This needs to be converted to a machine language which the computer can comprehend. This process of conversion is one of compiling the source code into object code, which then is passed to a linker, which combines one or more object files into an executable binary. The following process is illustrative:


lev@squirrel:~/programming/pascal$ fpc hello.pas
Free Pascal Compiler version 2.4.0-2 [2010/03/06] for i386
Copyright (c) 1993-2009 by Florian Klaempfl
Target OS: Linux for i386
Compiling hello.pas
Linking hello
/usr/bin/ld: warning: link.res contains output sections; did you forget -T?
6 lines compiled, 0.8 sec
lev@squirrel:~/programming/pascal$ ls
hello hello.o hello.pas
lev@squirrel:~/programming/pascal$ ./hello
Hello World


The command fpc is the Free Pascal Compiler. As the output explains the compilation creates an object file and then an executable. The error message is benign, as explained by the Free Pascal knowledge base. A directory listing shows the three files. When executed the hello binary produces the output "Hello World!".

Thursday, March 17, 2011

Introduction and Installation

This 'blog site provides a journal on using Free Pascal and Lazarus, the Delphi-compatible object development suite on a Linux system. It is designed to provide a practical introduction to structured and object-orientated programming with a language that is easy to learn, is free and open-source, and is in widespread use and development.

Pascal has been known since the 1970s as a language particularly good for educational purposes. It teaches people good programming practises which they should continue to use if they need to use other languages. A brief essay by Niklaus Wirth, the inventor of Pascal, explains its history.

In terms of other metrics, Pascal is readable and maintainable, but very powerful. Compared with other languages, Pascal has the advantages of quick compilation, fast executables, and low memory consumption. Free Pascal has excellent assembler integration for those who are super-programmers and highly portable, following the principles of "write once, compile anywhere (WOCA)".

There is no other language that can claim all these features. It is surprising, in my opinion, that Pascal is not the language of choice for most programmers.

This journal will begin with installation on Intel/i386 or AMD64/x86_64 CPUs. The most simple method of installation is package based, either through RedHat packages (rpms) or Debian packages (debs). Or one can install from source. The commands for the latter version are as follows:


root@squirrel:~# mkdir -p /usr/local/src/freepascal
root@squirrel:~# cd /usr/local/src/freepascal
root@squirrel:/usr/local/src/freepascal# wget ftp://ftp.freepascal.org/pub/fpc/dist/2.4.2/i386-linux/fpc-2.4.2.i386-linux.tar
root@squirrel:/usr/local/src/freepascal# tar xvf fpc-2.4.2.i386-linux.tar
root@squirrel:/usr/local/src/freepascal# ./install.sh


The shell script will provide all the options. The only variation from the default that I recommend is the installation path, which I used /usr/local/freepascal/2.4.2. To test to ensure installation simply type fp from the console. A text-based integrated development environment (IDE) should execute. Congratulations, you're on you're way towards programming in Pascal!