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.

No comments:

Post a Comment