Showing posts with label Pascal Tutorial. Show all posts
Showing posts with label Pascal Tutorial. Show all posts

Wednesday, 28 May 2014

Pascal - Units

Filled under:

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Pascal - Units

A Pascal program can consist of modules called units. A unit might consist of some code blocks, which in turn are made up of variables and type declarations, statements, procedures, etc. There are many built-in units in Pascal and Pascal allows programmers to define and write their own units to be used later in various programs.

Using Built-in Units

Both the built-in units and user-defined units are included in a program by the uses clause. We have already used the variants unit in Pascal - Variants tutorial. This tutorial explains creating and including user-defined units. However, let us first see how to include a built-in unit crt in your program:
program myprog;
uses crt;
The following example illustrates using the crt unit:
Program Calculate_Area (input, output);
uses crt;
var 
   a, b, c, s, area: real;
begin
   textbackground(white); (* gives a white background *)
   clrscr; (*clears the screen *)
   textcolor(green); (* text color is green *)
   gotoxy(30, 4); (* takes the pointer to the 4th line and 30th column) 
   writeln('This program calculates area of a triangle:');
   writeln('Area = area = sqrt(s(s-a)(s-b)(s-c))');
   writeln('S stands for semi-perimeter');
   writeln('a, b, c are sides of the triangle');
   writeln('Press any key when you are ready');
   readkey;
   clrscr;
   gotoxy(20,3);
   write('Enter a: ');
   readln(a);
   gotoxy(20,5);
   write('Enter b:');
   readln(b);
   gotoxy(20, 7);
   write('Enter c: ');
   readln(c);

   s := (a + b + c)/2.0;
   area := sqrt(s * (s - a)*(s-b)*(s-c));
   gotoxy(20, 9);
   writeln('Area: ',area:10:3);
   readkey;
end.
It is the same program we used right at the beginning of the Pascal tutorial, compile and run it to find the effects of the change.

Creating and Using a Pascal Unit

To create a unit, you need to write the modules or subprograms you want to store in it and save it in a file with .pas extension. The first line of this file should start with the keyword unit followed by the name of the unit. For example:
unit calculateArea;
Following are three important steps in creating a Pascal unit:
  • The name of the file and the name of the unit should be exactly same. So, our unit calculateAreawill be saved in a file named calculateArea.pas.
  • The next line should consist of a single keyword interface. After this line, you will write the declarations for all the functions and procedures that will come in this unit.
  • Right after the function declarations, write the word implementation, which is again a keyword. After the line containing the keyword implementation, provide definition of all the subprograms.
The following program creates the unit named calculateArea:
unit CalculateArea;
interface
function RectangleArea( length, width: real): real;
function CircleArea(radius: real) : real;
function TriangleArea( side1, side2, side3: real): real;

implementation
function RectangleArea( length, width: real): real;
begin
   RectangleArea := length * width;
end;

function CircleArea(radius: real) : real;
const
   PI = 3.14159;
begin
   CircleArea := PI * radius * radius;
end;

function TriangleArea( side1, side2, side3: real): real;
var
   s, area: real;
begin
   s := (side1 + side2 + side3)/2.0;
   area := sqrt(s * (s - side1)*(s-side2)*(s-side3));
   TriangleArea := area;
end;

end.
Next, let us write a simple program that would use the unit we defined above:
program AreaCalculation;
uses CalculateArea,crt;

var
   l, w, r, a, b, c, area: real;
begin
   clrscr;
   l := 5.4;
   w := 4.7;
   area := RectangleArea(l, w);
   writeln('Area of Rectangle 5.4 x 4.7 is: ', area:7:3);

   r:= 7.0;
   area:= CircleArea(r);
   writeln('Area of Circle with radius 7.0 is: ', area:7:3);

   a := 3.0;
   b:= 4.0;
   c:= 5.0;
   area:= TriangleArea(a, b, c);
   writeln('Area of Triangle 3.0 by 4.0 by 5.0 is: ', area:7:3);
end.
When the above code is compiled and executed, it produces the following result:
Area of Rectangle 5.4 x 4.7 is: 25.380
Area of Circle with radius 7.0 is: 153.938
Area of Triangle 3.0 by 4.0 by 5.0 is: 6.000

Posted By MIrza Abdul Hannan5:51:00 am

Pascal - Memory Management

Filled under:

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Pascal - Memory Management

This chapter explains dynamic memory management in Pascal. Pascal programming language provides several functions for memory allocation and management.

Allocating Memory Dynamically

While doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example, to store a name of any person, it can go max 100 characters so you can define something as follows:
var
name: array[1..100] of char;
But now, let us consider a situation, where you have no idea about the length of the text you need to store, for example, you want to store a detailed description about a topic. Here, we need to define a pointer to string without defining how much memory is required.
Pascal provides a procedure newto create pointer variables.
program exMemory;
var
name: array[1..100] of char;
description: ^string;
begin
   name:= 'Zara Ali';
   new(description);
      if not assigned(description) then
         writeln(' Error - unable to allocate required memory')
      else
         description^ := 'Zara ali a DPS student in class 10th';
   writeln('Name = ', name );
   writeln('Description: ', description^ );
end.
When the above code is compiled and executed, it produces the following result:
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
Now, if you need to define a pointer with specific number of bytes to be referred by it later, you should use the getmem function or the getmem procedure, which has the following syntax:
procedure Getmem(
   out p: pointer;
   Size: PtrUInt
);

function GetMem(
   size: PtrUInt
):pointer;
In the previous example, we declared a pointer to a string. A string has a maximum value of 255 bytes. If you really don't need that much space, or a larger space, in terms of bytes, getmem subprogram allows specifying that. Let us rewrite the previous example, using getmem:
program exMemory;
var
name: array[1..100] of char;
description: ^string;
begin
   name:= 'Zara Ali';
   description := getmem(200);
      if not assigned(description) then
         writeln(' Error - unable to allocate required memory')
      else
         description^ := 'Zara ali a DPS student in class 10th';
   writeln('Name = ', name );
   writeln('Description: ', description^ );
   freemem(description);
end.
When the above code is compiled and executed, it produces the following result:
Name = Zara Ali
Description: Zara ali a DPS student in class 10th
So, you have complete control and you can pass any size value while allocating memory unlike arrays, where once you defined the size cannot be changed.

Resizing and Releasing Memory

When your program comes out, operating system automatically releases all the memory allocated by your program, but as a good practice when you are not in need of memory anymore, then you should release that memory.
Pascal provides the procedure dispose to free a dynamically created variable using the procedurenew. If you have allocated memory using the getmem subprogram, then you need to use the subprogram freemem to free this memory. The freemem subprograms have the following syntax:
procedure Freemem(
   p: pointer;
  Size: PtrUInt
);

function Freemem(
   p: pointer
):PtrUInt;
Alternatively, you can increase or decrease the size of an allocated memory block by calling the functionReAllocMem. Let us check the above program once again and make use of ReAllocMem and freememsubprograms. Following is the syntax for ReAllocMem:
function ReAllocMem(
   var p: pointer;
   Size: PtrUInt
):pointer;   
Following is an example which makes use of ReAllocMem and freemem subprograms:
program exMemory;
var
name: array[1..100] of char;
description: ^string;
desp: string;
begin
   name:= 'Zara Ali';
   desp := 'Zara ali a DPS student.';
   description := getmem(30);
   if not assigned(description) then
      writeln('Error - unable to allocate required memory')
   else
      description^ := desp;

   (* Suppose you want to store bigger description *)
   description := reallocmem(description, 100);
   desp := desp + ' She is in class 10th.';
   description^:= desp; 
   writeln('Name = ', name );
   writeln('Description: ', description^ );
   freemem(description);
end.
When the above code is compiled and executed, it produces the following result:
Name = Zara Ali
Description: Zara ali a DPS student. She is in class 10th

Memory Management Functions

Pascal provides a hoard of memory management functions that is used in implementing various data structures and implementing low-level programming in Pascal. Many of these functions are implementation dependent. Free Pascal provides the following functions and procedures for memory management:
S.NFunction Name & Description
1function Addr(X: TAnytype):Pointer;
Returns address of variable
2function Assigned(P: Pointer):Boolean;
Checks if a pointer is valid
3function CompareByte(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
4function CompareChar(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
5function CompareDWord(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
6function CompareWord(const buf1; const buf2; len: SizeInt):SizeInt;
Compares 2 memory buffers byte per byte
7function Cseg: Word;
Returns code segment
8procedure Dispose(P: Pointer);
Frees dynamically allocated memory
9procedure Dispose(P: TypedPointer; Des: TProcedure);
Frees dynamically allocated memory
10function Dseg: Word;
Returns data segment
11procedure FillByte(var x; count: SizeInt; value: Byte);
Fills memory region with 8-bit pattern
12procedure FillChar( var x; count: SizeInt; Value: Byte|Boolean|Char);
Fills memory region with certain character
13procedure FillDWord( var x; count: SizeInt; value: DWord);
Fills memory region with 32-bit pattern
14procedure FillQWord( var x; count: SizeInt; value: QWord);
Fills memory region with 64-bit pattern
15procedure FillWord( var x; count: SizeInt; Value: Word);
Fills memory region with 16-bit pattern
16procedure Freemem( p: pointer; Size: PtrUInt);
Releases allocated memory
17procedure Freemem( p: pointer );
Releases allocated memory
18procedure Getmem( out p: pointer; Size: PtrUInt);
Allocates new memory
19procedure Getmem( out p: pointer);
Allocates new memory
20procedure GetMemoryManager( var MemMgr: TMemoryManager);
Returns current memory manager
21function High( Arg: TypeOrVariable):TOrdinal;
Returns highest index of open array or enumerated
22function IndexByte( const buf; len: SizeInt; b: Byte):SizeInt;
Finds byte-sized value in a memory range
23function IndexChar( const buf; len: SizeInt; b: Char):SizeInt;
Finds char-sized value in a memory range
24function IndexDWord( const buf; len: SizeInt; b: DWord):SizeInt;
Finds DWord-sized (32-bit) value in a memory range
25function IndexQWord( const buf; len: SizeInt; b: QWord):SizeInt;
Finds QWord-sized value in a memory range
26function Indexword( const buf; len: SizeInt; b: Word):SizeInt;
Finds word-sized value in a memory range
27function IsMemoryManagerSet: Boolean;
Is the memory manager set
28function Low( Arg: TypeOrVariable ):TOrdinal;
Returns lowest index of open array or enumerated
29procedure Move( const source; var dest; count: SizeInt );
Moves data from one location in memory to another
30procedure MoveChar0( const buf1; var buf2; len: SizeInt);
Moves data till first zero character
31procedure New( var P: Pointer);
Dynamically allocate memory for variable
32procedure New( var P: Pointer; Cons: TProcedure);
Dynamically allocates memory for variable
33function Ofs( var X ):LongInt;
Returns offset of variable
34function ptr( sel: LongInt; off: LongInt):farpointer;
Combines segment and offset to pointer
35function ReAllocMem( var p: pointer; Size: PtrUInt):pointer;
Resizes a memory block on the heap
36function Seg( var X):LongInt;
Returns segment
37procedure SetMemoryManager( const MemMgr: TMemoryManager );
Sets a memory manager
38function Sptr: Pointer;
Returns current stack pointer
39function Sseg: Word;
Returns stack segment register value

Posted By MIrza Abdul Hannan5:50:00 am

Pascal - File Handling

Filled under:

Post By: Hanan Mannan
Contact Number: Pak (+92)-321-59-95-634
-------------------------------------------------------

Pascal - File Handling

Pascal treats a file as a sequence of components, which must be of uniform type. A file's type is determined by the type of the components. File data type is defined as:
type
file-name = file of base-type;
Where, the base-type indicates the type of the components of the file. The base type could be anything like, integer, real, Boolean, enumerated, subrange, record, arrays and sets except another file type. Variables of a file type are created using the var declaration:
var
f1, f2,...: file-name;
Following are some examples of defining some file types and file variables:
type
   rfile = file of real;
   ifile = file of integer;
   bfile = file of boolean;
   datafile = file of record
   arrfile = file of array[1..4] of integer;
var
   marks: arrfile;
   studentdata: datafile;
   rainfalldata: rfile;
   tempdata: ifile;
   choices: bfile;

Creating and Writing to a File

Let us write a program that would create a data file for students' records. It would create a file named students.dat and write a student's data into it:
program DataFiles;
type
   StudentRecord = Record
      s_name: String;
      s_addr: String;
      s_batchcode: String;
   end;
var
   Student: StudentRecord;
   f: file of StudentRecord;

begin
   Assign(f,'students.dat');
   Rewrite(f);
   Student.s_name := 'John Smith';
   Student.s_addr := 'United States of America';
   Student.s_batchcode := 'Computer Science';
   Write(f,Student);
   Close(f);
end.
When compiled and run, the program would create a file named students.dat into the working directory. You can open the file using a text editor, like notepad, to look at John Smith's data.

Reading from a File

We have just created and written into a file named students.dat. Now, let us write a program that would read the student's data from the file:
program DataFiles;
type
   StudentRecord = Record
      s_name: String;
      s_addr: String;
      s_batchcode: String;
   end;
var
   Student: StudentRecord;
   f: file of StudentRecord;
begin
   assign(f, 'students.dat');
   reset(f); 
   while not eof(f) do
   begin
      read(f,Student);
      writeln('Name: ',Student.s_name);
      writeln('Address: ',Student.s_addr);
      writeln('Batch Code: ', Student.s_batchcode);
   end;
   close(f);
end.
When the above code is compiled and executed, it produces the following result:
Name: John Smith
Address: United States of America
Batch Code: Computer Science

Files as Subprogram Parameter

Pascal allows file variables to be used as parameters in standard and user-defined subprograms. The following example illustrates this concept. The program creates a file named rainfall.txt and stores some rainfall data. Next, it opens the file, reads the data and computes the average rainfall.
Please note that, if you use a file parameter with subprograms, it must be declared as a var parameter.
program addFiledata;
const
   MAX = 4;
type
   raindata = file of real;
var
   rainfile: raindata;
   filename: string;
procedure writedata(var f: raindata);
var
   data: real;
   i: integer;
begin
   rewrite(f, sizeof(data));
   for i:=1 to MAX do
   begin
      writeln('Enter rainfall data: ');
      readln(data);
      write(f, data);
   end;
   close(f);
end;

procedure computeAverage(var x: raindata);
var
   d, sum: real;
   average: real;
begin
   reset(x);
   sum:= 0.0;
   while not eof(x) do
   begin
      read(x, d);
      sum := sum + d;
   end;
   average := sum/MAX;
   close(x);
   writeln('Average Rainfall: ', average:7:2);
end;
begin
   writeln('Enter the File Name: ');
   readln(filename);
   assign(rainfile, filename);
   writedata(rainfile);
   computeAverage(rainfile);
end.
When the above code is compiled and executed, it produces the following result:
Enter the File Name:
rainfall.txt
Enter rainfall data:
34
Enter rainfall data:
45
Enter rainfall data:
56
Enter rainfall data:
78
Average Rainfall: 53.25

Text Files

A text file, in Pascal, consists of lines of characters where each line is terminated with an end-of-line marker. You can declare and define such files as:
type
file-name = text;
Difference between a normal file of characters and a text file is that a text file is divided into lines, each terminated by a special end-of-line marker, automatically inserted by the system. The following example creates and writes into a text file named contact.txt:
program exText;
var
   filename, data: string;
   myfile: text;
begin
   writeln('Enter the file name: ');
   readln(filename);
   assign(myfile, filename);
   rewrite(myfile);
   writeln(myfile, 'Note to Students: ');
   writeln(myfile, 'For details information on Pascal Programming');
   writeln(myfile, 'Contact: Tutorials Point');
   writeln('Completed writing'); 
   close(myfile);
end.
When the above code is compiled and executed, it produces the following result:
Enter the file name:
contact.txt 
Completed writing

Appending to a File

Appending to a file means writing to an existing file that already has some data without overwriting the file. The following program illustrates this:
program exAppendfile;
var
   myfile: text;
   info: string;
begin
   assign(myfile, 'contact.txt');
   append(myfile);
   writeln('Contact Details');
   writeln('hmragroupengineers@hmragroup.com');
   close(myfile);
   (* let us read from this file *)
   assign(myfile, 'contact.txt');
   reset(myfile);
   while not eof(myfile) do
   begin
      readln(myfile, info);
      writeln(info);
   end;
   close(myfile);
end.
When the above code is compiled and executed, it produces the following result:
Contact Details
webmaster@tutorialspoint.com
Note to Students:
For details information on Pascal Programming
Contact: Tutorials Point

File Handling Functions

Free Pascal provides the following functions/procedures for file handling:
S.NFunction Name & Description
1procedure Append( var t: Text ); 
Opens a file in append mode
2procedure Assign( out f: file; const Name: ); 
Assigns a name to a file
3procedure Assign( out f: file; p: PChar ); 
Assigns a name to a file
4procedure Assign( out f: file; c: Char ); 
Assigns a name to a file
5procedure Assign( out f: TypedFile; const Name: );
Assigns a name to a file
6procedure Assign( out f: TypedFile; p: PChar ); 
Assigns a name to a file
7procedure Assign( out f: TypedFile; c: Char );
Assigns a name to a file
8procedure Assign( out t: Text; const s: ); 
Assigns a name to a file
9procedure Assign( out t: Text; p: PChar ); 
Assigns a name to a file
10procedure Assign( out t: Text; c: Char ); 
Assigns a name to a file
11procedure BlockRead( var f: file; var Buf; count: Int64; var Result: Int64 ); 
Reads data from a file into memory
12procedure BlockRead( var f: file; var Buf; count: LongInt; var Result: LongInt ); 
Reads data from a file into memory
13procedure BlockRead( var f: file; var Buf; count: Cardinal; var Result: Cardinal ); 
Reads data from a file into memory
14procedure BlockRead( var f: file; var Buf; count: Word; var Result: Word ); 
Reads data from a file into memory
15procedure BlockRead( var f: file; var Buf; count: Word; var Result: Integer ); 
Reads data from a file into memory
16procedure BlockRead( var f: file; var Buf; count: Int64 ); 
Reads data from a file into memory
17procedure BlockWrite( var f: file; const Buf; Count: Int64; var Result: Int64 ); 
Writes data from memory to a file
18procedure BlockWrite( var f: file; const Buf; Count: LongInt; var Result: LongInt );
Writes data from memory to a file
19procedure BlockWrite( var f: file; const Buf; Count: Cardinal; var Result: Cardinal ); 
Writes data from memory to a file
20procedure BlockWrite( var f: file; const Buf; Count: Word; var Result: Word ); 
Writes data from memory to a file
21procedure BlockWrite( var f: file; const Buf; Count: Word; var Result: Integer ); 
Writes data from memory to a file
22procedure BlockWrite( var f: file; const Buf; Count: LongInt );
Writes data from memory to a file
23procedure Close( var f: file ); 
Closes a file
24procedure Close( var t: Text ); 
Closes a file
25function EOF( var f: file ):Boolean; 
Checks for end of file
26function EOF( var t: Text ):Boolean; 
Checks for end of file
27function EOF: Boolean; 
Checks for end of file
28function EOLn( var t: Text ):Boolean; 
Checks for end of line
29function EOLn: Boolean; 
Checks for end of line
30procedure Erase( var f: file ); 
Deletes file from disk
31procedure Erase( var t: Text ); 
Deletes file from disk
32function FilePos( var f: file ):Int64; 
Position in file
33function FileSize( var f: file ):Int64; 
Size of file
34procedure Flush( var t: Text ); 
Writes file buffers to disk
35function IOResult: Word; 
Returns result of last file IO operation
36procedure Read( var F: Text; Args: Arguments ); 
Reads from file into variable
37procedure Read( Args: Arguments ); 
Reads from file into variable
38procedure ReadLn( var F: Text; Args: Arguments ); 
Reads from file into variable and goto next line
39procedure ReadLn( Args: Arguments ); 
Reads from file into variable and goto next line
40procedure Rename( var f: file; const s: ); 
Renames file on disk
41procedure Rename( var f: file; p: PChar ); 
Renames file on disk
42procedure Rename( var f: file; c: Char ); 
Renames file on disk
43procedure Rename( var t: Text; const s: ); 
Rename file on disk
44procedure Rename( var t: Text; p: PChar ); 
Renames file on disk
45procedure Rename( var t: Text; c: Char ); 
Renames file on disk
46procedure Reset( var f: file; l: LongInt ); 
Opens file for reading
47procedure Reset( var f: file ); 
Opens file for reading
48procedure Reset( var f: TypedFile ); 
Opens file for reading
49procedure Reset( var t: Text );
Opens file for reading
50procedure Rewrite( var f: file; l: LongInt ); 
Opens file for writing
51procedure Rewrite( var f: file ); 
Opens file for writing
52procedure Rewrite( var f: TypedFile ); 
Opens file for writing
53procedure Rewrite( var t: Text ); 
Opens file for writing
54procedure Seek( var f: file; Pos: Int64 ); 
Sets file position
55function SeekEOF( var t: Text ):Boolean; 
Sets file position to end of file
56function SeekEOF: Boolean; 
Sets file position to end of file
57function SeekEOLn( var t: Text ):Boolean;
Sets file position to end of line
58function SeekEOLn: Boolean; 
Sets file position to end of line
59procedure SetTextBuf( var f: Text; var Buf ); 
Sets size of file buffer
60procedure SetTextBuf( var f: Text; var Buf; Size: SizeInt ); 
Sets size of file buffer
61procedure Truncate( var F: file ); 
Truncate the file at position
62procedure Write( Args: Arguments ); 
Writes variable to file
63procedure Write( var F: Text; Args: Arguments ); 
Write variable to file
64procedure Writeln( Args: Arguments ); 
Writes variable to file and append newline
65procedure WriteLn( var F: Text; Args: Arguments ); 
Writes variable to file and append newline

Posted By MIrza Abdul Hannan5:49:00 am