A/L 2011_revision. PASCAL PROGRAMMING
page 1 of 8
Pascal is a high level programming language developed by Niklaus Wirth in 1970 based on the ALGOL programming language. It was named in honor of the French mathematician and philosopher Blaise Pascal. Pascal programs saved as *.pas.
Variables store values/data
Constants stay the same
Control Flow change directions
Procedures sub routines
Functions sub routines returning a value
Comments notes
Structure of a Pascal program
PROGRAM ProgramName (FileList);uses crt; (*importing libraries)
const (* Constant declarations *)type
(* Type declarations *)var
(* Variable declarations *)(* Subprogram definitions *)begin (* Main Program statements *)end.
program FirstProg;
begin
Writeln('Hello World!');
end.
A/L 2011_revision. PASCAL PROGRAMMING
page 2 of 8
VARIABLES
Must begin with a letter
Can include alphanumeric characters and underscore (_).
May not contain ~ ! @ # $ % ^ & * ( ) + ` - = { } [ ] : " ; ' < > ? , . / |
CONSTANTS
Value assigned to a constant at the beginning of the program. It can’t be changed during the program running.
Const Pi = 3.1415926535897932; Gravity = 9.8; GoldenRatio = 1.6; a : real = 12;
A/L 2011_revision. PASCAL PROGRAMMING
page 3 of 8
VARIABLES AND DATA TYPES
Var IdentifierList1 : DataType1; IdentifierList2 : DataType2; IdentifierList3 : DataType3;
The basic data types
integer From -32768 to 32767
real () 3.4x10-38 to 3.4x1038
Char “A”
string “Niranjan”
Boolean TRUE and FALSE
var IndexNumber, Age: integer Temperature :real; FirstName: string; Married: Boolean
ASSIGNMENT AND OPERATIONS
variable_name := expression;
length := 385.38;
totalarea := (37.57 * 5.93) + (38.2/2.1);
A/L 2011_revision. PASCAL PROGRAMMING
page 4 of 8
OPERATORS
+ Addition- Subtraction* Multiplication/ Divisiondiv Integer divisionmod Modulus (remainder division)
PUNCTUATION AND INDENTATION
Pascal ignores end-of-lines and spaces.punctuation (;) tells the compiler when a statement ends.
program Compute; const a = 5; b = 385.3;
var alpha, beta : real;
begin (* main *) alpha := a + b; beta := b / aend. (* main *)
COMMENTS
(* one line *)(* some comments go into several lines*)
A/L 2011_revision. PASCAL PROGRAMMING
page 5 of 8
INPUT / OUTPUT
read (Variable_List); readln (Variable_List);
read (a); readln (b);read (a, b, c, d); readln (e, f);
write (Argument_List);writeln (Argument_List);
write (a);writeln (b,c,d);write ('Time:', time:2);
program InputOutput;
vara, b : string;begin (* main *) read(a); readln(b); writeln(a) writeln(a)end.
A/L 2011_revision. PASCAL PROGRAMMING
page 6 of 8
CONDITIONALS RELATIONAL OPERATORS:
<>=
<=>=<>
less than greater than
equal to less than or equal to
greater than or equal to not equal to
5 < 72 > 14=3+12<=310>=5“A” <>”B”
IF … THEN
if BooleanExpression then
Statement1;
if A = 30 then Writeln('A is equal to 30');
IF … THEN …. ELSE
if BooleanExpression then StatementIfTrue
else
StatementIfFalse;
if A = 30 then
Writeln('A is equal to 30')
else
Writeln('A is not equal to 30');
A/L 2011_revision. PASCAL PROGRAMMING
page 7 of 8
NESTED IF
if Condition1 then
Statement1
else
if Condition2 then
Statement2
else
Statement3;
if A=30 then
Writeln('A is equal to 30');
else
if A=50 then
Writeln('A is equal to 50');
else
Writeln('A is not 30 or 50');
CASE
case selector of
List1: Statement1;
List2: Statement2;
...
Listn: Statementn;
otherwise Statement
end;
Choice := ReadKey;
case Choice of 'a': Writeln('You like apples'); 'b': Writeln('You like bananas'); 'c': Writeln('You like carrots');else Writeln('Your choice is not a, b or c');
A/L 2011_revision. PASCAL PROGRAMMING
page 8 of 8
LOOPINGFOR NEXT
for index := Low to High do statements;
sum := 0;
for count := 1 to 100 do sum := sum + count;
WHILE .. DO
while BooleanExpression do
begin statements;
end.
a := 5;
while a < 6 do
writeln (a);
a := a + 1
REPEAT … UNTIL
repeat statement1;
until BooleanExpression;
a := 5;
repeat a := a + 1; writeln (a);until a > 10
GOTO
LABEL 10; statements;
GOTO 10;
A/L 2011_revision. PASCAL PROGRAMMING
page 9 of 8
BREAK and CONTINUE
The Break command will exit a loop at any time.
program breakTest; var i: Integer;begin i := 0; repeat i := i + 1; break; Writeln(i);until i = 10;end.
program breakTest; var i: Integer;begin i := 0; repeat i := i + 1; continue; Writeln(i);until i = 10;end.
Program 1 will not print anything because break it exits the loop before it gets there.
In Program 2 continuecommand will jump back to the top of a loop
ARRAYS
var
X: ARRAY [1..5] of real;begin
X[1]:=4.2; X[2]:=71.6; X[3]:=8.3; X[4]:=92.6; X[5]:=403.7; writeln (X[1]+X[2]+X[3]+X[4]+X[5])
end.
A/L 2011_revision. PASCAL PROGRAMMING
page 10 of 8
PROCEDURES & FUNCTIONSProcedure has the same basic format as a program:
procedure Name;
const (* Constants *)
Var(* Variables *)
Begin (* Statements *)end;
Parameters to the procedure passed in the heading
procedure PrintParameters (a, b : integer; c, d : real);
begin a := 10; b := 2; writeln (a, b, c, d)end;
FUNCTIONS
function functionName (parameter_list) : return_type; statements;
function add1toParameter(a) : integer;begin add1toParameter:= a + 1end.
BUILT IN FUNCTIONS
abs returns absolute valuearctan returns arctan in radianscos returns cosine of a radian measuresin returns sin of a radian measuresqr returns square (power 2) sqrt returns root (power 1/2)chr character with given ASCII value round returns round to nearest integer
A/L 2011_revision. PASCAL PROGRAMMING
page 11 of 8
MATH FUNTIONSABS(-6) the absolute value of -6; gives 6SQR(3) the square of 3; gives 9SQRT(9) the square root of 9; gives 3.0SIN(2) the sine of 2 radians measureCOS(2) the cosine of 2 radians measureLN(9) the natural logarithm of 9; gives loge 9ROUND(9.2) rounds a number; gives 9
Functions are used to do repetitive tasks to reduce repeating code.
program AddEmUpAgain;
function AddEmUp( a, b, c: integer ) : integer;
begin AddEmUp := a + b + c; end;
procedure PrintData( a, b, c: integer );
begin Writeln('The sum of a, b, and c is ', AddEmUp(a, b, c), '.'); end;
begin
PrintData(2, 3, 4);
end.
A/L 2011_revision. PASCAL PROGRAMMING
page 12 of 8
SAMPLE PROGRAMS
Find the sum and average of five numbers
program SumAverage;
const
NumberOfIntegers = 5;
var
A, B, C, D, E : integer; Sum : integer; Average : real;
begin (* Main *)
A := 45; B := 7; C := 68; D := 2; E := 34; Sum := A + B + C + D + E;
Average := Sum / NumberOfIntegers; writeln ('Number of integers = ', NumberOfIntegers); writeln ('Number1 = ', A); writeln ('Number2 = ', B); writeln ('Number3 = ', C); writeln ('Number4 = ', D); writeln ('Number5 = ', E); writeln ('Sum = ', Sum); writeln ('Average = ', Average)
end. (* Main *)
A/L 2011_revision. PASCAL PROGRAMMING
page 13 of 8
Input 5 numbers and print their sum and average
program SumAverage;
const
NumberOfIntegers = 5;
var
A, B, C, D, E : integer; Sum : integer; Average : real;
begin (* Main *)
write ('Enter the first number: '); readln (A); write ('Enter the second number: '); readln (B); write ('Enter the third number: '); readln (C); write ('Enter the fourth number: '); readln (D); write ('Enter the fifth number: '); readln (E);
Sum := A + B + C + D + E;
Average := Sum / 5; writeln ('Number of integers = ', NumberOfIntegers); writeln; writeln ('Number1:', A:8); writeln ('Number2:', B:8); writeln ('Number3:', C:8); writeln ('Number4:', D:8); writeln ('Number5:', E:8); writeln ('================'); writeln ('Sum:', Sum:12); writeln ('Average:', Average:10:1);
end.
A/L 2011_revision. PASCAL PROGRAMMING
page 14 of 8
SCOPEWhere will the variables be visible?
program ScopeDemo;var A, B : integer;
procedure ScopeInner; begin B:= 10; writeln (B); (* prints value 10 *) writeln (A); (* prints value 20 *)end;
begin (* Main *) A := 20; writeln (A); (* prints value 20 *) ScopeInner; (*changes A value*) writeln (A); (* prints new value 10*)end. (* Main *)
global variables A visible everywhereglobal variables can be changed inside procedures.
A/L 2011_revision. PASCAL PROGRAMMING
page 15 of 8
RCURSIONRecursion allows a function or procedure to call itself
function Sum (num : integer) : integer;begin if num = 1 then Sum := 1else Sum := Sum(num-1) + num;(* calls self again*)end;
begin totalsum:=Sum(10); writeln(totalsum);end.
If we call Sum with 3 as parameter
totalsum := Sum(3);
1st call : Sum(3) becomes Sum(2) + 3.
2nd call : Sum(2) becomes Sum(1) + 2.
At 1, the recursion stops and becomes 1 and returns
Sum(2) becomes 1 + 2 = 3.
Sum(3) becomes 3 + 3 = 6.
a becomes 6.
A/L 2011_revision. PASCAL PROGRAMMING
page 16 of 8
FORWARD REFERENCING
procedures/functions can only use variables and subprograms already defined before them. (this is a weakness in Pascal coding)
procedure Second (parameter list); procedure First (parameter list);procedure Third (parameter list);
procedure First;begin Second (parameter list);(*Second is declared before First *)end;
procedure Second;begin Third (parameter list); (* ERROR Third is not visible to Second*)end;
A/L 2011_revision. PASCAL PROGRAMMING
page 17 of 8
Find the first 100 numbers in the Fibonacci sequence. 1 1 2 3 5 8 13 21 …..
program Fibonacci;
var
Fibonacci1, Fibonacci2 : integer; temp : integer; count : integer;
begin (* Main *)writeln ('First ten Fibonacci numbers are:');count := 0;Fibonacci1 := 0;Fibonacci2 := 1;
repeat write (Fibonacci2:7); temp := Fibonacci2; Fibonacci2 := Fibonacci1 + Fibonacci2; Fibonacci1 := Temp; count := count + 1until count = 10;
writeln;
(*you can also use a FOR loop or a WHILE loop. *)
end. (* Main *)
ASSIGNMENT
Modify above program to display all powers of 2 up to 200.What code would you change and why?
A/L 2011_revision. PASCAL PROGRAMMING
page 18 of 8
FILE HANDLINGReading and Writing to Files
read (file_variable, argument_list);write (file_variable, argument_list); rest (file_variable, 'filename' ) rewrite (file_variable, 'filename'); assign (file_variable, 'filename');eoln (file_variable) eof (file_variable)
Reads values from a fileWrite values to a fileOpens a file for reading Opens a file for writingAssigns a filename to a variableReturns TRUE when end of line is reachedReturns TRUE when end of file is reached
program CopyOneByteFile;
var mychar : char; filein, fileout : text;
begin assign (filein, 'c:\file1.txt'); reset (filein); assign (fileout, 'c:\file2.txt'); rewrite (fileout); read (filein, mychar); write (fileout, mychar); close(filein); close(fileout)end.
A/L 2011_revision. PASCAL PROGRAMMING
page 19 of 8
BOOLEAN EXPRESSIONS
not and or xor
negation conjunction disjunctionexclusive-or
(~) (^) (v)
NOT applied to only one value to invert it:
NOT true = false NOT false = true
AND gives TRUE only if both values are TRUE:
TRUE and FALSE = FALSE TRUE and TRUE = TRUE
OR yields TRUE if at least one value is TRUE:
TRUE or TRUE = TRUE TRUE or FALSE = TRUE FALSE or TRUE = TRUE FALSE or FALSE = FALSE
XOR yields TRUE if one expression is TRUE and the other is FALSE.
TRUE xor TRUE = FALSE TRUE xor FALSE = TRUE FALSE xor TRUE = TRUE FALSE xor FALSE = FALSE
A/L 2011_revision. PASCAL PROGRAMMING
page 20 of 8
Bubble sort moves the biggest numbers to the end of the array.Example of Sorting 5 Numbers
program BubbleSort;
var
a: array[1..5] of Integer;
i, j, tmp: Integer;
begin
a[1] := 23; a[2] := 45; a[3] := 12; a[4] := 56; a[5] := 34;
for i := 1 to 4 do
for j := i + 1 to 5 do
if a[i] > a[j] then
begin
tmp := a[i]; a[i] := a[j]; a[j] := tmp; end;
for i := 1 to 5 do
writeln(i,': ',a[i]);
end.
A/L 2011_revision. PASCAL PROGRAMMING
page 21 of 8
Programming Solution: the Towers of Hanoi Problem
program TowersofHanoi;
var numdiscs : integer;
procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer);(* Explanation of variables Number of discs -- number of discs on OrigPeg OrigPeg -- peg number of the tower NewPeg -- peg number to move the tower to TempPeg -- peg to use for temporary storage*)
begin (* Take care of the base case -- one disc *)
if NumDiscs = 1 then writeln (OrigPeg, ' ---> ', NewPeg) (* Take care of all other cases *)else begin (* First, move all discs except the bottom disc to TempPeg, using NewPeg as the temporary peg for this transfer *)
DoTowers (NumDiscs-1, OrigPeg, TempPeg, NewPeg);
(* Now, move the bottom most disc from OrigPeg to NewPeg *)
writeln (OrigPeg, ' ---> ', NewPeg);
(* Finally, move the discs currently on TempPeg to NewPeg, use OrigPeg as the temporary peg for this transfer *)
DoTowers (NumDiscs-1, TempPeg, NewPeg, OrigPeg) endend;
begin (* Main *) write ('Please enter the number of discs in the tower ===> ') readln (numdiscs); writeln; DoTowers (numdiscs, 1, 3, 2)end. (* Main *)
Tower of Hanoi is a problem with three pegs and more than 3 disks on one peg.
You have to move disks one by one from peg to peg to transfer all disks to one peg.
Rules1. Only one disk can be transferred at a time.
2. Smaller disk should always be on the top of the other.
A/L 2011_revision. PASCAL PROGRAMMING
page 22 of 8
program Decisions;
var i: Integer;
begin Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5');end.
program Decisions;
var i: Integer;
begin Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5') else Writeln('Not greater than 5');end.
program Loops1;
var i: Integer;
begin i := 0; while i <= 10 begin i := i + 1; Writeln('Hello'); end;end.
program Loops2;
var i: Integer;
begin i := 0; repeat i := i + 1; Writeln('Hello'); until i = 10;end.
Download FREE Pascal
http://www.freepascal.org
Created by: Niranjan Meegammana, Shilpa Sayura Project. Supported by YES & ICT @ OSIPTO, KANDY.www.shilpasayura.org