CSCI 150, Spring 2003
Home | | Course Schedule | | Assignments | | Lecture NotesExample:
program calcCube; procedure Cube( n: integer; var result: integer); begin result := n * n * n; end; var number: integer; answer: integer; begin writeln('Enter a number: '); readln(number); Cube(number, answer); writeln('The cube of ', number, ' is ', answer); end.
2. Procedures with local variables.
A procedure may have local variables in addition to the parameters. The local variables are listed
just below the procedure header. The variables are local to the procedure, so they cannot be
accessed by any other procedure or by the main program.
Example:
program volumeFinder; procedure WriteVolume( r, h: real ); var volume: real; begin volume := 3.14159 * r * r * h; writeln( 'The volume is ', volume); end; var radius, height: real; begin writeln('Enter the radius and height: '); readln(radius); readln(height); WriteVolume( radius, height ); end.
3. Functions.
Functions are subprograms that return a value. They behave like procedures in most respects,
except they return a value to the calling program. The type of value returned is specified at the end
of the function header. The name of the function is used like a variable within the function
definition. At the end of the function execution the value of this identifier is returned to the calling
program.
Example:
program calcCube; function Cube( n: integer ): integer; {Return a value of type integer } begin Cube := n * n * n; {the value of Cube will be returned } end; var number: integer; begin writeln('Enter a number: '); readln(number); writeln('The cube of ', number, ' is ', Cube(number)); end.
Another Example:
program circles; function Area( r: real ): real; begin Area := 3.14159 * r * r; end; var materialCost: real; radius: real; totalCost: real; begin writeln('Enter the radius of the circle: '); readln(radius); writeln('Enter the cost of the material: '); readln(materialCost); totalCost := Area( radius ) * materialCost; writeln('The total cost to fill the circle with the material is ', totalCost:10:2); end.