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 Constants Control Flow Procedures Functions Comments store values/data stay the same change directions sub routines sub routines returning a value notes Structure of a Pascal program PROGRAM ProgramName (FileList); uses crt; (*importing libraries) const (* Constant declarations *) type (* Type declarations *) (* Variable declarations *) (* Subprogram definitions *) (* Main Program statements *) program FirstProg; Writeln('Hello World!'); page 1 of 8
VARIABLES CONSTANTS Must with a letter Can include alphanumeric characters and underscore (_). May not contain ~! @ # $ % ^ & * ( ) + ` - = { } [ ] : " ; ' < >?,. / Value assigned to a constant at the ning 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; page 2 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.4x10 38 Char string Boolean A Niranjan TRUE and FALSE IndexNumber, Age: integer Temperature :real; FirstName: string; Married: Boolean ASSIGNMENT AND OPERATIONS iable_name := expression; length := 385.38; totalarea := (37.57 * 5.93) + (38.2/2.1); page 3 of 8
OPERATORS + Addition - Subtraction * Multiplication / Division div Integer division mod 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; alpha, beta : real; (* main *) alpha := a + b; beta := b / a (* main *) COMMENTS (* one line *) (* some comments go into several lines*) page 4 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; a, b : string; (* main *) read(a); readln(b); writeln(a) writeln(a) page 5 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 < 7 2 > 1 4=3+1 2<=3 10>=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'); page 6 of 8
NESTED IF if Condition1 then Statement1 else if Condition2 then Statement2 if A=30 then Writeln('A is equal to 30'); else if A=50 then Writeln('A is equal to 50'); else Statement3; else Writeln('A is not 30 or 50'); CASE case selector of List1: Statement1; List2: Statement2;... Listn: Statementn; 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'); otherwise Statement page 7 of 8
LOOPING FOR NEXT for index := Low to High do statements; sum := 0; for count := 1 to 100 do sum := sum + count; WHILE.. DO while BooleanExpression do statements; 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; page 8 of 8
BREAK and CONTINUE The Break command will exit a loop at any time. program breaktest; i: Integer; i := 0; repeat i := i + 1; break; Writeln(i); until i = 10; program breaktest; i: Integer; i := 0; repeat i := i + 1; continue; Writeln(i); until i = 10; Program 1 will not print anything because break it exits the loop before it gets there. In Program 2 continue command will jump back to the top of a loop ARRAYS X: ARRAY [1..5] of real; 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]) page 9 of 8
PROCEDURES & FUNCTIONS Procedure has the same basic format as a program: procedure Name; const (* Constants *) Var (* Variables *) Begin (* Statements *) Parameters to the procedure passed in the heading procedure PrintParameters (a, b : integer; c, d : real); a := 10; b := 2; writeln (a, b, c, d) FUNCTIONS function functionname (parameter_list) : return_type; statements; BUILT IN FUNCTIONS function add1toparameter(a) : integer; add1toparameter:= a + 1 abs returns absolute value arctan returns arctan in radians cos returns cosine of a radian measure sin returns sin of a radian measure sqr returns square (power 2) sqrt returns root (power 1/2) chr character with given ASCII value round returns round to nearest integer page 10 of 8
MATH FUNTIONS ABS(-6) the absolute value of -6; gives 6 SQR(3) the square of 3; gives 9 SQRT(9) the square root of 9; gives 3.0 SIN(2) the sine of 2 radians measure COS(2) the cosine of 2 radians measure LN(9) the natural logarithm of 9; gives log e 9 ROUND(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; AddEmUp := a + b + c; procedure PrintData( a, b, c: integer ); Writeln('The sum of a, b, and c is ', AddEmUp(a, b, c), '.'); PrintData(2, 3, 4); page 11 of 8
SAMPLE PROGRAMS Find the sum and average of five numbers program SumAverage; const NumberOfIntegers = 5; A, B, C, D, E : integer; Sum : integer; Average : real; (* 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) (* Main *) page 12 of 8
Input 5 numbers and print their sum and average program SumAverage; const NumberOfIntegers = 5; A, B, C, D, E : integer; Sum : integer; Average : real; (* 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); page 13 of 8
SCOPE Where will the iables be visible? program ScopeDemo; A, B : integer; procedure ScopeInner; B:= 10; writeln (B); (* prints value 10 *) writeln (A); (* prints value 20 *) (* Main *) A := 20; writeln (A); (* prints value 20 *) ScopeInner; (*changes A value*) writeln (A); (* prints new value 10*) (* Main *) global iables A visible everywhere global iables can be changed inside procedures. page 14 of 8
RCURSION Recursion allows a function or procedure to call itself function Sum (num : integer) : integer; if num = 1 then Sum := 1 else Sum := Sum(num-1) + num;(* calls self again*) totalsum:=sum(10); writeln(totalsum); If we call Sum with 3 as parameter totalsum := Sum(3); 1 st call : Sum(3) becomes Sum(2) + 3. 2 nd 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. page 15 of 8
FORWARD REFERENCING procedures/functions can only use iables 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; Second (parameter list);(*second is declared before First *) procedure Second; Third (parameter list); (* ERROR Third is not visible to Second*) page 16 of 8
Find the first 100 numbers in the Fibonacci sequence. 1 1 2 3 5 8 13 21.. program Fibonacci; Fibonacci1, Fibonacci2 : integer; temp : integer; count : integer; (* 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 + 1 until count = 10; writeln; (*you can also use a FOR loop or a WHILE loop. *) (* Main *) ASSIGNMENT Modify above program to display all powers of 2 up to 200. What code would you change and why? page 17 of 8
FILE HANDLING Reading and Writing to Files read (file_iable, argument_list); write (file_iable, argument_list); rest (file_iable, 'filename' ) rewrite (file_iable, 'filename'); assign (file_iable, 'filename'); eoln (file_iable) eof (file_iable) Reads values from a file Write values to a file Opens a file for reading Opens a file for writing Assigns a filename to a iable Returns TRUE when end of line is reached Returns TRUE when end of file is reached program CopyOneByteFile; mychar : char; filein, fileout : text; assign (filein, 'c:\file1.txt'); reset (filein); assign (fileout, 'c:\file2.txt'); rewrite (fileout); read (filein, mychar); write (fileout, mychar); close(filein); close(fileout) page 18 of 8
BOOLEAN EXPRESSIONS not and or xor negation conjunction disjunction exclusive-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 page 19 of 8
Bubble sort moves the biggest numbers to the end of the array. Example of Sorting 5 Numbers program BubbleSort; a: array[1..5] of Integer; i, j, tmp: Integer; 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 tmp := a[i]; a[i] := a[j]; a[j] := tmp; for i := 1 to 5 do writeln(i,': ',a[i]); page 20 of 8
Programming Solution: the Towers of Hanoi Problem program TowersofHanoi; numdiscs : integer; procedure DoTowers (NumDiscs, OrigPeg, NewPeg, TempPeg : integer); (* Explanation of iables 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*) (* Take care of the base case -- one disc *) if NumDiscs = 1 then writeln (OrigPeg, ' ---> ', NewPeg) (* Take care of all other cases *) else (* First, move all discs except the bottom disc to TempPeg, using NewPeg as the temporary peg for this transfer *) 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. Rules 1. Only one disk can be transferred at a time. 2. Smaller disk should always be on the top of the other. 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) end (* Main *) write ('Please enter the number of discs in the tower ===> ') readln (numdiscs); writeln; DoTowers (numdiscs, 1, 3, 2) (* Main *) page 21 of 8
program Decisions; i: Integer; Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5'); program Decisions; i: Integer; Writeln('Enter a number'); Readln(i); if i > 5 then Writeln('Greater than 5') else Writeln('Not greater than 5'); program Loops1; i: Integer; i := 0; while i <= 10 i := i + 1; Writeln('Hello'); program Loops2; i: Integer; i := 0; repeat i := i + 1; Writeln('Hello'); until i = 10; Download FREE Pascal http://www.freepascal.org Created by: Niranjan Meegammana, Shilpa Sayura Project. Supported by YES & ICT @ OSIPTO, KANDY. www.shilpasayura.org page 22 of 8