Pascal Programming: Week 6 Notes Evaluating Expressions Previous Example: IF (Value <> 0) AND (Answer DIV Value >= 20) THEN Writeln(' Incorrect'); Fix: IF (Value <> 0) THEN IF (Answer DIV Value >= 20) THEN Writeln(' Incorrect'); a:= sqr(b) * h - c + b; b:= a + c * b; c:= b - h * h; h:= h - h; b:= b - c * TRUNC(e); c:= c DIV ROUND(e); h:= h MOD ROUND(e); IF (b > c) OR (b < h) AND (h < a) THEN {do something} f:= f / e * 3.5 + 2.0; x:= x + e + x * x; e:= e / 4.0 * 2.1 + 1.7; Functions Pre-defined: SQR(), SQRT(), TRUNC(), ROUND(), and others User-defined: CUBE() example FUNCTION Cube(x: integer): integer; BEGIN Cube:= x*x*x; END; {Cube} FUNCTION Factorial(x: integer):integer; VAR i,temp: integer; BEGIN temp:= x; FOR i:= x DOWNTO 2 DO BEGIN temp:= temp * (x-1); x:=x-1; END; Factorial:= temp; END; {factorial} Functions are expressions Written like a procedure but it returns a value FUNCTION Factorial(x: longint):longint; VAR temp: longint; i: integer; BEGIN temp:= x; CASE temp OF 0: Factorial:= 1; 1: Factorial:= 1; ELSE BEGIN FOR i:= x DOWNTO 2 DO BEGIN temp:= temp * (x-1); x:=x-1; END; {for loop} Factorial:= temp; END; {else clause} END; {case statement} END; {function factorial} Arrays One-Dimensional Array Declaration Usage of arrays Example: TYPE Days = (mon, tues, wed, thu, fri, sat, sun); SmArray = Array[1..5] of Days; VAR Index: Integer; List: Array[1..100] of Integer; Week: Array[1..7] of Days; WeekDays: SmArray; BEGIN {program} Writeln('Enter in the last seven days you worked'); FOR i:= 1..7 DO Readln(Week[i]); Write('The listing of days worked is '); WHILE I > 0 DO BEGIN Write(Week[i]); i:= I-1; END; {while} Writeln; END. {program} User-Defined Types Overview of Type Declaration Example: CONST Noon = 12.00; TYPE Money = Real; Time = Real; Name = String(10); Grade = 'A' .. 'F'; Score = 0..100; PosInt = 0..maxint; Days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); VAR PayDue: Money; PROCEDURE GetPayDue (VAR Pay: Money, Rate: Real); BEGIN {do something} END; {GetPayDue} More Number Types in Turbo Pascal pg. 558 shortint -128..127 interger -32768..32767 longint -2147483648..2147483647 byte 0..255 word 0..65535 real 2.9*10-39 .. 1.7*1038 single 1.5*10-45 .. 3.4*1038 double 5.0*10-324 .. 1.7*10308 extended 3.4*10-4932 .. 1.1*104932 Must set E and N compiler directive: {$N+,E+} Units Overview of Unit Declaration Interface Part Procedure Heading and Documentation Implementation Part Procedure Heading and Body Initialization Part Private Variable Initialization Example: Chapter 8 pg. 276-305