Tuesday, December 8, 2009

18. More Graphics with Free Pascal

The following program generates circles and ellipses. By using random numbers for colors and delayed activation of pixels on the screen, I tried to paint a pleasing picture. The static(standard) graphics commands are in the main program and the variable calls for activating pixels(pictures) are in the createcircles procedure. The program follows:

Program program18;
{Author: Rao S Lakkaraju}
{Graphics with Pascal}
Uses Crt,Graph;

Var GraphicsDriver, GraphicsMode,
n,radius,radius1,radius3 : Integer;
ax,ay,ar : integer;

Procedure Createcircles;
Begin
Outtextxy(120,30,'My Beautiful Painting');

setcolor(red);
setfillstyle(1,red);
rectangle(75,120,510,570);
radius1 := 0;
ax := getmaxx div 2;
ay := getmaxy div 2;


for radius := 50 to 100 do begin

SetColor(Random(14) + 1);
radius1 := radius ;
ar := radius div 2;
Outtextxy(120,30,'My Beautiful Painting');

{Left Side}
rectangle(10+ar,70+ar,200+ax-ar,290+ay-ar);
circle(ax-280, ay, radius1);
circle(ax-280, ay, radius1-49);
circle(ax-280, ay, radius1+55);
ellipse(ax-280, 420+radius1, 0,360,150,40);
ellipse(ax-280, 120+radius1, 0,360,150,40);

{ellipse(x1,y1,degreesfrom,degrees to,hr,vr)}
{ Right Side}

circle(ax, ay, radius1);
circle(ax , ay - radius1- ar, ar );
circle(ax , ay + radius1+ ar, ar );
ellipse(430, 220+radius1, 0,360,60,60);
ellipse(430+150, 220+radius1, 0,360,60,60);
ellipse(430, 220+2*radius1+30, 0,360,60,40);
ellipse(430+150, 220+2*radius1+30, 0,360,60,40);
delay(300 );

end;
End;

Begin
ClrScr;
Writeln('Graphics Initialization');
GraphicsDriver := Detect;
InitGraph(GraphicsDriver, GraphicsMode,'');
ClearViewPort;
Randomize;
SetColor(cyan);
settextstyle(triplexfont,horizdir,2);
for n:= 1 to 1 do begin

ClearViewPort;
createcircles; delay(300); end;

SetColor(cyan);
settextstyle(triplexfont,horizdir,1);
OutTextXY(135,70,'Is It not Wonderful ????');
OutTextXY(580,580,'lakkaraju');
Readln;
CloseGraph;

End.

Summary: Graphics is activation of pixels on the screen. Simply sketch it on paper . transform into rectangles, circles and ellipses with proper coordinates and colors. Now vary some of the coordinates and colors; A beautiful picture comes out in real time, as you imagined.

Tuesday, November 24, 2009

17. Free Pascal Graphics

In the previous post we learned the fundamentals of graphics and were able to do basic painting on the screen. In this post we use the same instructions to create circles etc. and use delay and loops to create visual effects. Study the program17 and play with it.

There are two procedures in the program. First procedure createcircles creates circles etc. The second procedure destroycircle destroys the created circle and also creates more visuals while destroying the circle.

The main program is just initiating graphics, declaring variables, calling the procedures and closing the Graphical unit.

Study the two procedures and play with them and enjoy creating your own paintings. Use delay and variation of pixel coordinates for visual effects.

Always remember Graphics is just activation of pixels on the screen. Screen is your canvas and use your imagination and mathematical formulae for timing the activation and deactivation of pixels.

Program program17;
{Author: Rao S Lakkaraju}
{Graphics with Pascal}
Uses Crt,Graph;

Var GraphicsDriver, GraphicsMode,
x,y,radius,radius1,radius3 : Integer;

Procedure Createcircles;
Begin
setcolor(yellow);
rectangle(100,120,510,570);
radius1 := 0;
Outtextxy(20,40,' Creating Circles');

For radius := 1 to 200 do
Begin
while radius1 <> radius then begin SetColor(black); {Set text colour}
Circle(GetMaxX Div 2, GetMaxY Div 2, Radius3);
radius3 := radius - 5;
SetColor(Random(15) + 1);
Circle(100,200, Radius3 div 2);
{ellipse(x1,y1,degreesfrom,degrees to,hr,vr)}
ellipse(250,330 + radius3 ,0,360,80,40);
pieslice(370,570,20,80,radius3 div 2+40);
Delay(905 );
setfillstyle(1,red);
bar(240,570,260, radius3 + 300 );
{pieslice(x,y,p,q,radius)}
pieslice(430,200,20,80,radius3 div 2+40);
end; end;
End;


Begin
ClrScr;
Writeln('Graphics Initialization');
GraphicsDriver := Detect;
InitGraph(GraphicsDriver, GraphicsMode,'');
ClearViewPort;
Randomize;
SetColor(cyan);
settextstyle(triplexfont,horizdir,2);
OutTextXY(20,20,'Welcome to the Disappearing Circle');


createcircles;
destroycircle;

SetColor(cyan);
OutTextXY(20,80,' I am done');
Readln;
CloseGraph;

End.

SUMMARY: Graphics is just activating the pixels on the screen. We can use delay, color and timing in activating the pixels to give visual effects. Your paint brush is your program, control the paint brush movements and you get an excellent pictures on the screen.

Saturday, November 21, 2009

16. Basic Graphics in Free Pascal

Graphics is just painting on the screen, the screen has pixels in it and we put light on individual pixels. Each pixel on the screen has a position (x,y), where x and y are the x,y coordinates of the pixel. Top left corner is the lowest pixel coordinate (0,0) and the bottom right corner is the highest pixel coordinate (1023,711). We can activate any pixel in the screen with any color we want. If we light the pixels on the circle, we get a circle on the screen. Basically Graphics is lighting the right pixels on the screen.

In order to write a Graphics program in Pascal, we have to do three special steps.

First, we have to use graphical unit.
uses crt,graph;

Second, we have to initialize the graphical unit.
grdriver := DETECT;
initgraph(grdriver,grmode, ' ' );

Third, we have to give instructions to the graph unit to paint on the screen.
settextstyle(triplexfont,horizdir,2);
OutTextXY(50,30,'Graphics With Pascal');

In the following program I wrote, I experimented with basic shapes and colors. All the instructions for graphical pictures are in the procedure graphicpics. Study the program and do your own experiments.

Program program16;
{Author: Rao S Lakkaraju}
{* Basic Graphics Program *}

uses crt,graph;
var grmode, grdriver :integer;
x,y : integer;

Procedure graphicpics;
Begin
{Now give instructions to do graphics}

randomize;
settextstyle(triplexfont,horizdir,1);
for x := 1 to 200 do begin putpixel(49+x,500,(random(15))); end;


setcolor(Lightgreen);

settextstyle(triplexfont,horizdir,2);
OutTextXY(50,30,'Graphics With Pascal');
settextstyle(triplexfont,horizdir,1);
OutTextXY(50,300,'Screen Coordinates');
OutTextXY(50,350,'Top left corner (x,y): 0,0');
OutTextXY(50,400,'Bottom right corner (x,y): 1023,711 Pixels');
writeln('max x = ', getmaxx,' max y = ', getmaxy);

setfillstyle(1,red);
bar(100,100,250,250);
setfillstyle(2,green);
bar(0,0,23,19);
bar(1000,690,1023,711);

setcolor(red);
{line(x1,y1,x2,y2)}
line(0,0,0,23);
line(0,0,23,0);
for x := 1000 to 1023 do putpixel(x,711,red);
for y := 690 to 711 do putpixel(1023,y,red);
for x := 800 to 850 do putpixel(x,500,red);
for y := 450 to 500 do putpixel(850,y,red);
setcolor(cyan);
{rectangle(x1,y1,x2,y2);}
Rectangle(50,150,80,250);

{circle(x1,y1,radius); x1,y1 center of the circle}
circle(80,180,50);

{ellipse(x1,y1,degreesfrom,degrees to,hr,vr)}
ellipse(150,200,0,360,30,40);

{arc(x,y,p,q,radius)}
arc(180,250,0,90,60);

{pieslice(x,y,p,q,radius)}
pieslice(150,150,20,95,100);
End;


begin
{First we have to initialize the graphics mode}

clrscr;
grdriver := DETECT;
initgraph(grdriver,grmode, ' ' );

graphicpics;

Writeln('**** My Sixteenth Pascal Program ****');
readln;
CloseGraph;
end.

Summary: Graphics is simple painting on the screen. Pascal has all the basics of drawing geometric shapes(Line, Rectangle, Circle, Ellipse, Arc etc) using basic colors (red, white etc). Pleasing graphics is a combination of these basic shapes and a little imagination of placing them on the screen.

Thursday, November 19, 2009

15. Recursive programming in Free Pascal

Recursion is the process of working on a procedure repeatedly until we reach a solution. For example if you want to find out the sum of numbers starting from 1 increasing by 1 until 6, we start with 1 and make it as temporary sum and add to it 2,3 etc until we reach 6. The sum now gives the value we want.
We can also get the sum doing reverse computation. We start with 6(n) as the temporary sum and add to it 5(n-1) , decreasing 6 by 1.
Thus sum of 1 thru 6 is: sum(6) := 6 + sum 1 thru 5.
We keep on doing this repeatedly (recursive) until we reach 1, where we know the answer, the sum of a series of numbers starting with 1 and ends in 1, is 1.
if n =1 then sum := 1
Once we reach sum(1) = 1, we go back and solve all the equations and find the value of sum(6).

sum := n + sum(n-1);
sum(6) := 6 + sum(5),
sum(5) := 5 + sum(4) ,
sum(4) := 4 + sum(3),
sum(3) := 3 + sum(2),
sum(2) := 1 + sum(1),
sum(1) := 0 + 1 ** We know the answer for sum(1) and go backwards and solve the problem.

The main points in recursive programming is: Doing repeatedly the same process until we reach a condition to break the repetition. The condition is important because, if it is not there we will be repeatedly calling the process until we fill up the memory and crash.

Program15 Illustrates Recursive programming with two recursive functions sum and fact.

if n = 1 then sum := 1 else sum := n + sum(n-1);

if n = 0 then fact := 1 else fact := n * fact(n-1);

Program 15 follows:

Program program15;
{Author: Rao S Lakkaraju}
{Recursive Programming}
uses crt;

var n,m : integer;

function sum (n:integer) :integer;
begin
writeln('n is ',n);
if n = 1 then sum := 1 else sum := n + sum(n-1);
Writeln('sum is ',sum);
end;

function fact(n:integer) : integer;
begin
if n = 0 then fact := 1 else
fact := n * fact(n-1);
end;

begin
clrscr;
write('Please enter an integer to sum to ');
readln(n);
m := sum(n);
writeln('Sum of 1 to ',n,' is ',m);

write('Please enter an integer for factorial ');
readln(n);
m := fact(n);
writeln('Factorial of ',n,' is ',m);
Writeln( '**** My fifteenth Pascal Program ****');
readln;
end.

SUMMARY: Recursive programming is calling a known process repeatedly until we reach an end condition. We should know the process and the end condition where that process stops, otherwise we end up nowhere like driving a car without knowing where to stop.

Thursday, November 12, 2009

14. Binary Tree Lists in Free Pascal

A binary tree is an extension of Link List. Basic Link List has only one link attached to the Node whearas basic Binary tree has two links attached to the Link(Node). The very first link in the tree forms the root of the tree, has a data and two link addresses showing the next links. The rule of Link attachments are: If data in current link(Link to be attached) > root data, current link is attached to the right if not it is attached to the left.

1. First the link is described with a type declaration as having a data and two link pointers right and left. root,temp,current are pointer variables are the type link.

type point = ^link;
link = record
data : integer;
right : point;
left : point;
end;

var i : integer;
root,temp,current : point;

2. The main program is to create tree root and get links to attach to the root.

createroot;
getlink ;

3. Read input integer and create root.

Procedure createroot;
Begin
Write('enter root integer = ');
readln(i);
new(root);
root^.data := i;
root^.right := nil;
root^.left := nil;
end;


4. Make links and attach to the tree. We create a current link and call addnode to add to the tree.

Procedure getlink ;
begin

for i := 1 to 5 do begin

new(current);
current^.data := i;
current^.right := nil;
current^.left := nil;

addnode(i,root);
readln;
end;
end;{end getlink }

6. In addnode we compare data of current node to be attached to the root and attach the node if the next address is vacant. If it can not be attached, start calling addnode with failed node address until vacant node is found for attaching the current node.

Procedure addnode( i : integer; temp : point );
begin
writeln;
write('i=',i,' trying to add node value: ',i,' at as= ',temp^.data,' ',i);


if i > temp^.data then if temp^.right = nil then
begin writeln(' right'); temp^.right := current; end
else addnode(i,temp^.right);

if i <= temp^.data then if temp^.left = nil then
begin writeln(' left'); temp^.left := current; end
else addnode(i,temp^.left);

end;


6. Program follows: If you run the program it will ask you for an integer to create the root node.

Program Program14;
(* Author: Rao S Lakkaraju *)
(* Pointer Basics _ Binary trees *)
uses crt,graph;

type point = ^link;
link = record
data : integer;
right : point;
left : point;
end;

var i : integer;
root,temp,current : point;


Procedure createroot;
Begin
Write('enter root integer = ');
readln(i);
new(root);
root^.data := i;
root^.right := nil;
root^.left := nil;
end;

Procedure addnode( i : integer; temp : point );
begin
writeln;
write('i=',i,' trying to add node value: ',i,' at as= ',temp^.data,' ',i);


if i > temp^.data then if temp^.right = nil then
begin writeln(' right'); temp^.right := current; end
else addnode(i,temp^.right);

if i <= temp^.data then if temp^.left = nil then begin writeln(' left'); temp^.left := current; end else addnode(i,temp^.left); end; Procedure getlink ; begin for i := 1 to 5 do begin new(current); current^.data := i; current^.right := nil; current^.left := nil; addnode(i,root); readln; end; end;{end getlink } Procedure displayorder (root : Point); begin IF root <> nil then begin

displayorder(root^.Left);
write(root^.Data);
displayorder(root^.Right);

end;
end;
{ Main Program Begins}

begin
clrscr;

createroot;
getlink ;

Write('Display tree Nodes: ');
Displayorder(root);
writeln;
Writeln('My fourteenth Pascal Program');

readln;
end.

Summary: Binary Trees in Pascal are just ordered Link Lists. The order is if the data in the current link is greater than the data in the last link, it is attached to the right of the last link otherwise attached to the left. With this rule in mind we traverse the tree(visit the links) starting from the root for a vacant spot to hang the branch(Link).

Monday, November 9, 2009

13. Link Lists in Free Pascal

Creating Link Lists in Pascal is very easy with pointers.

1.First define the link as a record type. It will have two areas. A data area and a pointer area.
type point = ^link;
link = record
data : integer;
next : point;
end;

2. Define variables for Link Record. We need three pointer variables of type link to track the growth of the List, first, last and current.
var i : integer;
first,last,current : point;

3. Create the Link Record and make it as the current record for linking to the list. If there is no first record, make the current record as first and last records in the List. When we create the next current link , we just replace the last record's next pointer by the current record pointer and make the current record as the last record, effectively increasing the links by 1.

new(current);
current^.data := i;
current^.next := nil;
if first = nil then first := current
else last^.next := current;

last := current;

4. we can create links, display them and dispose them too in this simple way.
for i:= 1 to 10 do
createlinks(i);

Displaylinks;
disposelinks;

5. Program13 follows:



Program program13;
(* Author: Rao S Lakkaraju *)
(* Pointer Basics - Link Lists *)
uses crt,graph;

type point = ^link;
link = record
data : integer;
next : point;
end;

var i,linktot : integer;
first,last,current : point;

Procedure createlinks(i:integer);
begin
new(current);
current^.data := i;
current^.next := nil;
if first = nil then first := current
else last^.next := current;

last := current;
linktot := linktot + 1;

writeln('last data= ', last^.data);

end;

Procedure Displaylinks;
begin

textbackground(white);
textcolor(red);

Current := first;
repeat
write(current^.data, ' ');
current := current^.next;
until current = nil;
end;

Procedure disposelinks;
{ Store next link address and dispose first link}
{Make next link address as first link}
{Repeat until there are no more next links}
begin
repeat
{current := first;}
current := first^.next;
dispose(first);
first := current^.next;
until first = nil;
end;

begin
clrscr;
first := nil;
linktot := 0;

for i:= 1 to 10 do
createlinks(i);

Displaylinks;
disposelinks;

writeln;
writeln('Total Links in the List = ',linktot);
writeln('My thirteenth Pascal program');
readln;
end.


SUMMARY: It is very easy to create links in Pascal. Create a typed record with desired elements in it, the last element should be a pointer to link to the next record. Keep track of first, Last and current records while adding to the List. We will have a linked list in Pascal in no time.

Thursday, November 5, 2009

12. Pointer Basics in Free Pascal

In Pascal there is what is called dynamic allocation of memory. We reserve space when we need it and dispose it off after using it. As each space in memory has an address, we grab the addresses depending upon our needs and dispose them when they are no longer needed.

Just like integer variables which store integers only, Pointer variables store only addresses in Pascal. Just like we use variables to manipulate values in them we manipulate pointer variables also with their values(addresses). Additionally with pointers, we can manipulate the values in spaces they point in the memory.

First we have to declare them just like anything else.
Ex: var p,q : ^integer;
the ^ before integer saying that p and q are pointers which store only addresses of integer spaces in memory.

Next we grab space in memory for pointers.
ex: new(p);
Give me new space to store integer and put that address in pointer p.

Next put an integer(3) in that space.
ex: p^ := 3;
p^ means put 3 in the space specified by the address in p.

Make pointer q also contain same address as p. ex: q := p;

Now get a new space for p. store 4 in it. ex: new(p); p^:= 4;

Display the contents of spaces pointed by p and q with writeln. ex: writeln('p = ', p^,' q = ',q^);

After we are done finished using spaces, we can dispose the spaces.
ex: dispose(p); dispose(q);

The following program describes all.

Program Program12;
(* Author: Rao S Lakkaraju *)
(* Pointer Basics *)
uses crt,graph;

var p,q : ^integer; { declares p and q as an integer pointer variables }

begin
clrscr;
new(p); { allot space for an integer for pointer p }
p^ := 3; { Dereference p to store integer 3 in that location }
q := p; { make pointer q pointing to the same location as p }
new(p); {allot another space for an integer for pointer p }
p^:= 4; (* store 4 in that location*)

{ Display the value in the location pointed by p and q }
writeln('p = ', p^,' q = ',q^);

dispose(p); { destroy pointer p and release memory }
dispose(q); (* destroy pointer q and release memory *)

writeln('My twelth Pascal program');
readln;
end.

Summary: Pointer variables are used for dynamic allocation of memory in Pascal. We can grab the memory we need, we use the space as we need and dispose it off after our use. Since we placed the memory addresses in pointers, pointers are our contacts to the memory spaces.

Tuesday, November 3, 2009

11. TYPE DATA RECORD files in Pascal

A group of variables can be put together to form a record and that record can be described to pascal as a type of occurrence just like integer or string.
For example a description of members of an organisation could be handled as a type. Each member has a name, a city he came from, the state where that city located and the zip code of the city. This group of information describes a member of that group. This is a member record. This can be described as a type.

Type
memberec = Record
name,city,state : string;
zip : string;
End;
Once you defined it to pascal, we can use that record type in the program by assigning a variable to it. just like we declare variables of type integer. We also declare memberfile consists of all these member records.

var
memberfile : file of memberec;
filerec, seekrec :memberec;

Now we can use it just like any type . Since it consists of a group of variables, we have to specify which variable we want by dotting.
ex: filerec.name
etc.

The following a program which generates a number of member records of a type and reads them afterwords and displays them. The file is a random data file and assigned a name and opened for reading or writing. The record numbering starts with zero and continues. We use seek and record number to access a particular record. and read it to get the data.
seek(memberfile,indx);
read(memberfile,seekrec);

Program program11;
(* Author: Rao S Lakkaraju *)
(* Record Types and Data Files *)
uses crt,graph;

Type
memberec = Record
name,city,state : string;
zip : string;
End;
var
memberfile : file of memberec;
filerec, seekrec :memberec;

indx : integer;
sindx : string;

Procedure displayrec(filerec : memberec);
begin
write(filerec.name);
write(filerec.city);
write(filerec.state);
writeln(filerec.zip);
end;

Procedure writemember( filerec : memberec);

begin

for indx := 0 to 5 do
begin
str(indx,sindx);
filerec.name := sindx + 'rao';
filerec.city := sindx + 'aurora';
filerec.state:= sindx + 'IL';
filerec.zip := sindx + '60504';
displayrec(filerec);
write(memberfile,filerec);
end;

end;


Begin
clrscr;
textBackground(white);
Assign(memberfile, 'c:\member.dat');
ReWrite(memberfile);
Textcolor(Red);
writeln('Generated File Records');
writemember(filerec);
textcolor(green);
writeln('Seek file records');
indx:= 0;

repeat
seek(memberfile,indx);
read(memberfile,seekrec);
displayrec(seekrec);
indx := indx + 1;
until eof(memberfile);


writeln('My eleventh Pascal Program');
readln;
End.

Summary: A logical group of pascal variables could be described as a type and that type could be used in a pascal program by assigning a variable to it. The records of this type could be stored in a data file and accessed randomly for reading and writing.

Sunday, November 1, 2009

10. Files in Pascal ---- Text Files

Sometimes we have to store information externally, say on a hard disk than the computer memory which gets wiped out after the program ends execution. For that purpose Pascal provids some commands.

1. Give names to files and declare them as variables: Var filein, fileout : text;

2. We have to assign these file names to actual physical files on disk and open the files.
assign (filein, 'c:\file1.txt');
rewrite(filein); (* open for writing *)
reset (filein); (* Open file for reading *)
append(filein); (* Open file for adding records to it at the end *)

3. We can use read, readln, write, writeln commands to read and write the files. We have to say which files we are reading and writing.
writeln(filein, is +'AuroraRao');

4. After using the files we have to close them.
close(filein); close(fileout);


5. To make the content different in a record, a string conversion to the record added as the first character of the new record.
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');


6. The following program creates filein with records, reads the created records and copies them to fileout and appends records to filein at the end.



Program Program10;
{Author: Rao S Lakkaraju}
(* Program to demonstrate text Files *)
{**** Text File Handling ****}
uses crt,graph;
var
myrec,is : string;
filein, fileout : text;
indx : integer;

begin
clrscr;
(* creates an input file --- Writes records to an input file *)
(* Reads records from input file *)
(* and writes to an output file *)
writeln('Records in the file');
assign (filein, 'c:\file1.txt');
rewrite(filein);
assign (fileout, 'c:\file2.txt');
rewrite (fileout);

for indx := 1 to 5 do
begin
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');
writeln(filein, is +'Zipcode');
writeln(filein, is +'third record');
end;

close(filein);
reset (filein);


Repeat
readln (filein, myrec);
writeln(myrec);
writeln (fileout, myrec);
until eof(filein);

close(filein);
(* Append records to filein *)
append(filein);
for indx := 6 to 8 do
begin
str(indx,is); (* convert indx into string *)
writeln(filein, is +'AuroraRao');
end;
close(filein);
close(fileout);
readln;
end.

Summary: Pascal can create files on hard disk. For text files we can use read, readln, write, writeln commands for reading and writing. We have to tell which files we are reading and which files we are writing to in the commands.

Tuesday, October 27, 2009

9. Arrays in Pascal

If we want to store 5 names in the computer, we have to name them (name1,name2 etc.) and assign values to them individually. To retrieve also we have to retrieve them individually. Imagine how tedious it is going to be if we are writing a program to do pay roll for a walmart.

To make life easy, Pascal gave us, array. Pascal reserves space as indicated in the array definition and allowed us to access the space through an index. There are two ways of defining an array:

1. Here I defined a type called numbers with 15 spaces reserved

type numbers = array[1..15] of integer;

Here I equated a variable to numbers array

var numb : numbers;


2. var name :array[1..20] of string;
(* Here I defined array named name with 20 spaces*)

Following program describes the manipulation of arrays in Pascal:
Program program9;
(*Author: Rao S Lakkaraju*)
(* My pascal program9*)
{ Example of arrays }
uses crt,graph;

type numbers = array[1..15] of integer;
var numb : numbers;
name :array[1..20] of string;
index1 : integer;

begin
clrscr;
textbackground(white);
textcolor(red);
writeln(' My pascal program9');
writeln(' Array Values');

for index1 := 1 to 10 do
begin
numb[index1] := index1 + 1;
write(numb[index1]);
end;

writeln;
writeln('please enter name');
readln(name[1]);

for index1 := 2 to 10 do
begin
name[index1] := name[1]+ name[index1 - 1] ;
write(name[index1]);
writeln('yes');
end;

readln;
end.

Summary: Best way to store multiple values of a same type of variable in Pascal is the array[]. Pascal reserves space depending on the size and type of the array. We can use an index to store and retrieve values for processing.

Monday, October 26, 2009

8. Procedures in Pascal

We can look at the Pascal procedures as extensions to pascal functions except we do not assign value to the function name. Another difference is if we define multiple parameters in the procedure, each should be ended by a semicolon.
Here is a program which includes a procedure for converting minutes into hours and minutes. I introduced two new statements for crt, textbackground(white) and textcolor(red). The program is self explanatory.

Program program8;
(*Author: Rao S Lakkaraju*)
{ My pascal program 8 }

uses crt,graph;
var minutes : integer;

(* Procedure for converting minutes into hour and minutes *)

procedure time(minutes : integer);
var hr,min : integer;

begin
hr := minutes div 60;
min := minutes - hr * 60;
writeln;
textbackground(white);
textcolor(red);
write(minutes,' minutes equal to ', hr:2,' hours and ');
write(min:2, ' minutes');
writeln;
end;


{ Main Program Begins here }
begin
clrscr;
writeln(' My eigth pascal program ');
writeln('Please enter minutes ');
readln(minutes);

(*Call to the Procedure*)
time(minutes);

readln;
end.

Summary: If multiple statements are repeatedly used in a program, they could be put together to form a named procedure and be called by simply the procedure name wherever the statements are needed. Calling the procedure is simple, procedure name with parameters in parenthesis.

Sunday, October 25, 2009

7. Functions in Pascal

If we want to do same thing again and again, we write all the instructions to do that job at one place and call them whenever it is needed. In Pascal we have two language structures, functions and procedures, for repetitive tasks. Basically we write code to calculate the value with generic variables and give a name to it. We call the code using the given name with parameters if any whenever we need it.

Here we write the function to return square of a given number. The code follows:
function sqr(z : integer) : integer; begin sqr:= z * z; end;
z is an integer parameter. We can add more parameters with "," in between. The function name sqr declared as integer gets assigned the value of the computation. We call this function by inserting function name.
EX: y := sqr(x);

Program Program7;
{ My seventh pascal program }

uses crt,graph;
var x,y : integer;


function sqr(z:integer) : integer;
begin
sqr := z * z;
end;

{ Program Begins Here}
begin
clrscr;
writeln('My seventh Pascal program');

for x := 1 to 10 do
begin
y := sqr(x);
writeln('square of ':10,x:4, ' is ', y:4);
end;

readln;

end.

Summary: Pascal functions are used to package repetitive instructions and call them when they are needed. Every function have a name. The body begins with a begin followed by statements and ends with end;The computed value is returned to the name of the function with the specified type.

Saturday, October 24, 2009

6. Output Manipulation

We use computers to do complex things faster and would like to present results in a prettier looking understandable format. There are various techniques to do that and we will examine one by one.

1. Using a writeln statement without any parameters to skip a line. EX: writeln;

2. Using string variables in a writeln statement.
Ex: writeln('First Name Last Name'); **** Prints heading First Name Last Name as written in the string.

3. Using field parameters for variables in writeln statement.
Ex: writeln('First name' : 10, 'Last Name' : 12);
Write First Name in 10 spaces. Write Last Name in 12 spaces. Right justified always.

4. using field parameter for decimal places in the case of real numbers.
Ex: writeln('number3= ': 10, number3 :12:2);
Write the string number3= in 10 spaces and the number3 real variable in 12 places with 2 decimals.

In the case of wrong space field specification, computer will correct and display the whole value of the variable.

Program using these techniques follows:

Program program6;
(*Author: Rao S Lakkaraju*)
{ This is my sixth pascal program }
(* Output Manipulation in Pascal *)
uses crt,graph;
var n,number1, number2,number3 : integer;
interest1, interest2,interest3 : real;
name1, name2, name3 : string;
rich : boolean;

(* Program begins here *)
begin
clrscr;
number1 := 1;
number2 := 10;
interest1 := 2.5;
interest2 := 5.4;
name1 := 'Rao';
name2 := ' Lakkaraju';

(**** Lesson 4 *****)
for number3 := number1 to number2 do write(number3);

write(' ');

for number3 := number2 downto number1 do begin write(number3); end;

writeln(' ');
name3 := name1 + name2;
interest3 := interest1 + interest2;

textbackground(white);
textcolor(Red);

Writeln('number1 = ', number1);
writeln('number2 = ', number2);
writeln('number3 = ', number3);
writeln('interest1 = ', interest1, ' interest2 = ', interest2);
writeln('interest3 = ', interest3);
writeln('My Name is ', name3);

(**** Lesson 5 *****)
rich := false;
if not rich then writeln('I am not rich ')
else writeln('I am rich');

while rich = false do rich := true;

n := 1;
repeat n := n + 1; Writeln('I am in repeat'); until n = 8;

n := 2;
case n of 2,3,6 : writeln('value of n is ', n);
otherwise writeln('end of case'); end;

(**** Lesson 6 *****)
writeln;
writeln('First Name' : 10, 'Last Name':12);
writeln;
writeln(name1:10, name2:12);
writeln;
writeln('interest3=' :10, interest3:12:2);
writeln;
writeln('My sixth Pascal Program');
readln;

(* Program ends here *)
end.

Summary: Output from write statements can be formatted by specifying field lengths for each variable to be printed.

Friday, October 23, 2009

5. Condition processing in Pascal

There is another type of variable in pascal called boolean. It can have only two values, true or false. A statement which results in a true or false value is a boolean expression. ex: n = 8 results in a true value for the expression if n equalto 8. Note the equalto (=) sign in the expression which is different from assignment sign(:=).

Pascal provides language structures to control conditional processing. They are as follows:

1. if --condition-- then --statement1-- else --statement2--;
condition could be a = 10 or boolean. Notice the equal(=) sign in the condition.
Statement1 may not have ';' at the end, if it is followed by else. If it has results could be what you do not expect.

2. while --condition-- do --statement;
As long as the While condition is satisfied the statement processing continues. As such the condition should be changed in the statement otherwise the processing continues for ever.

3. Repeat ---- statements ---- until ---- boolean expression ----;
As noted in While the boolean expression value should change sometime or other, otherwise processing continues for ever.

4. Case --variable-- of --vales of variable-- : statement1; otherwise statement2; end;
ex: case n of 2,3,6 : writeln('value of n is ', n); otherwise writeln('end of case'); end;
For values of n equal to 2,3 or 6 write (value of n is) otherwise write (end of case).

Program depicting the conditional statements follows:

Program program5;
{ Author: Rao S Lakkaraju }
{ This is my fifth pascal program }
(* Condition Processing in Pascal *)

uses crt,graph;
var n,number1, number2,number3 : integer;
interest1, interest2,interest3 : real;
name1, name2, name3 : string;
rich : boolean;

begin
clrscr;
number1 := 1;
number2 := 10;
interest1 := 2.5;
interest2 := 5.4;
name1 := 'Rao';
name2 := ' Lakkaraju';

(**** Lesson 4 *****)
for number3 := number1 to number2 do write(number3);
write(' ');
for number3 := number2 downto number1 do begin write(number3); end;
writeln(' ');
name3 := name1 + name2;
interest3 := interest1 + interest2;
Writeln('number1 = ', number1);
writeln('number2 = ', number2);
writeln('number3 = ', number3);
writeln('interest1 = ', interest1, ' interest2 = ', interest2);
writeln('interest3 = ', interest3);
writeln('My Name is ', name3);

(**** Lesson 5 *****)
rich := false;
if not rich then writeln('I am not rich ')
else writeln('I am rich');
while rich = false do rich := true;
n := 1;
repeat n := n + 1; Writeln('I am in repeat'); until n = 8;
n := 2;
case n of 2,3,6 : writeln('value of n is ', n);
otherwise writeln('end of case'); end;

writeln('My fifth Pascal Program');
readln;
end.

Summary: Pascal provides a variable called boolean which could have only two values true or false. A boolean expression is one which after evaluation results in a boolean true or false value . Pascal provides statement execution depending on the value of a boolean expression. These pascal structures are if, while, repeat and case.

Thursday, October 22, 2009

4. Manipulating Pascal Variables

Variable name implies that it can take many values. The way we do that is to assign values at different times by an assignment statement like num1 := 10;. Writing multiple statements for assigning values is a cumbersome affair. For this purpose pascal has a for statement. It comes in two flavours, we can increase the value of a variable in steps of 1 or decrease the value of a variable in steps of one.

In the following program the for statements are self explanatory. After do we can have only one statement. If we want to have a bunch of statements after the do, we use the begin, multiple statements, end;. We can also see how strings are added. I want to mention write statement writes on the same line whereas writeln moves to a different line after writing the line.

Program Follows:
Program program4;
(* Author: Rao S Lakkaraju *)
{ This is my fourth pascal program }
(* Manipulating Pascal Variables *)
uses crt,graph;
var number1, number2,number3 : integer;
interest1, interest2,interest3 : real;
name1, name2, name3 : string;

begin
clrscr;
number1 := 1;
number2 := 10;
interest1 := 2.5;
interest2 := 5.4;
name1 := 'Rao';
name2 := ' Lakkaraju';
for number3 := number1 to number2 do write(number3);
write(' ');
for number3 := number2 downto number1 do begin write(number3); end;
writeln(' ');
name3 := name1 + name2;
interest3 := interest1 + interest2;
Writeln('number1 = ', number1);
writeln('number2 = ', number2);
writeln('number3 = ', number3);
writeln('interest1 = ', interest1, ' interest2 = ', interest2);
writeln('interest3 = ', interest3);
writeln('My Name is ', name3);

writeln('My fourth Pascal Program');
readln;
end.

Summary: We can vary the value of a pascal variable by using for statements. we can use begin... end; block to put together a bunch of pascal statements for execution as a block. We can add string variables.

Wednesday, October 21, 2009

3. Variables in Pascal

Variables are entities which vary in their life time. For example Numbers, they could be 1 to 10,000 or they could be 1.25 to 10000.85. Characters could be A to Z or ARAM to Zooram. So the computer needs to know what type of variable we are dealing with or manipulating in the program.

numbers 1 to say 10000 which do not have a decimal are called INTEGER. Those which have decimal are called REAL. variables which represent a group of characters are called STRING.

Let us make a program with variables. Our aim is to use 3 types of variables and print their values using Pascal program. Here is the program. Try it on your computer.



Program program3;
uses crt,graph;
var number1, number2 : integer;
var interest1, interest2 : real;
var name1, name2 : string;
{ This is my third pascal program }
begin
clrscr;
number1 := 21;
number2 := 1004;
interest1 := 2.5;
interest2 := 5.4;
name1 := 'Rao';
name2 := 'Lakkaraju';
Writeln('number1 = ', number1);
writeln('number2 = ', number2);
writeln('interest1 = ', interest1, ' interest2 = ', interest2);
writeln('My Name is ', name1, ' ', name2);

writeln('My third Pascal Program');
readln;
end.

The symbol ' :=' is called assignment symbol. number1 := 21 means number1 = 21.
name1 := 'Rao' is an assignment but it is a string assignment.
Uses crt,graph; I want the computer to use crt and graphics related language also.
clrscr; means clear the screen before writing. I am using crt language.

Summary: Variables are three types, integer,real and string. integer numbers are numbers without decimals, real numbers are numbers with decimals and string variables are combination of characters. by enclosing combination of characters by quotation marks, we can assign to a string variable, ex: 'David'.

Tuesday, October 20, 2009

2. How to write a pascal program

In general if we want to get anything done by someone, we have to tell exactly what we want. Same is the case with the computers more so than anything else. Unless we specify what we want exactly in the language it can understand, computer can not do our work. If it does the work, the results may be unpredictable and there is no meaning in blaming the computer for our short comings. Following are the steps you consider before telling the computer:

1. First we have to write down what the computer has to do for us.

2. Next we have to determine what basic materials the computer needs to do that work.

3. Next we have to tell the computer step by step what to do with those basic materials to produce the product we desire. Remember computer does things faster than us. If we give wrong instructions, it will give wrong results faster.

Let us try a program. We write a line saying " My first pascal program".
We are going to use pascal compiler. We write instructions for the computer to print "My first pascal program".

Program follows:

Program program1;
{ This is my first program }
begin
writeln(' My first pascal program ');
readln;
end.

Program program2;
uses crt,graph;
var number1, number2 : integer;
var interest1, interest2 : real;
var name1, name2 : string;
{ This is my second program }
begin
writeln('My second Pascal Program');
readln;
end.





The first line of the program says: Program name is program1. Notice the semi colon. Every statement ends with a semi colon ";".Exception is last statement "end.". It ends with a period '.'.

The second statement is a comment. Comments are enclosed by "{" and "}". Notice we do not put any semicolon. Comments are not compiled by the compiler.

The beginning of a program begins with "begin" and ends with "end.".
In between these two we have to give instructions to the computer.we have two instructions. They are called statements.

First statement is to write a line: "My first pascal program".

Second statement is to go to the next line and wait for my input. If we do not put this statement, the computer writes the line " My first pascal program". The second statement makes the computer wait for our input so that we can see the line. Just press ENTER on the key board and the execution goes to next statement.

The final statement is "end." which states this is the end of the program. The execution is complete.

Summary:Pascal program consists of statements, each specifying a step to be done by the computer. Each statement ends with a semi colon(;). The first statement 'Program' states the name of the program to the computer. The program starts with 'begin' and ends with 'end.'. In between these two we can write statements to the computer.

Monday, October 19, 2009

1. Pascal compiler

There are multiple flavors of Pascal compilers. I downloaded a free open source Pascal compiler for WINDOWS (latest release 2.2.4) and installed it. This is very easy to do.
Please go to the following site for the down load:

http://www.freepascal.org/download.var

Once you downloaded it and installed the Pascal compiler, you will see a Free Pascal IDE icon, FPC icon on the computer screen. Double click the icon and you will see a IDE screen to input your Pascal program. Please study various options on the top of the screen. We will be using FILE EDIT RUN COMPILE options very extensively.

The cursor is always at an insert character position. We can type in any characters we want. Using Edit, we can edit the information we entered just like in any editor.

Once a program is ready we can Compile the instructions we typed for machine language translation or use RUN for compiling and executing the Object(machine language instructions).

Sunday, October 18, 2009

0. Introduction

All computers work using a language called machine language. These machine language instructions are etched into computer chips.The instructions of the machine language consists of zeros and ones as the computer understands only binary(0,1). These binary instructions are very cumbersome and difficult to remember.

Scientists created what is called an ASSEMBLER language which has simple English equivalents to binary instructions, like ADD to add two numbers or SUM to sum two numbers. They designed what is called a translator which converts these instructions into binary computer instructions.And the computer will do whatever we want by executing these machine instructions. Still it is difficult to write instructions step by step in assembler.

To make languages much more friendlier using common day today English words, scientists started incorporating their laboratory lingo into computer languages and created translators to convert these instructions into binary machine language. The translator is called a COMPILER. This is the origin of higher level languages.First language designed with this concept is FORTRAN which stands for formula translation. If you write instructions in FORTRAN, like a=b+c etc, the translator translates these instructions into machine language instructions which the computer executes. The set of instructions we write in the language is called a computer program.The art of writing these instructions is called programming.

Many higher languages were developed after FORTRAN. COBOL for Business people,SPSS for statisticians,GRAPHICS to manipulate pictures on the crt screen etc. As the demand for computer processing grew, the need for people to write instructions in various languages grew. These people are called programmers and the need of programmers became acute as computers became work horses, doing routine work.

Pascal is a language developed to teach students various complexities in programming for the computers. Once you have the basics you can adopt them to any language you choose depending upon your profession.