Functions in Turing


A function is a subprogram with zero, one, or many input parameters.  The input parameters can be of any data type.  A function will return a single value of a specified data type.

 

The input parameters to a function are never changed by the function.  The only new value is the return value of the function itself.

 

To declare a function, you must specify the return data type (e.g., integer, string, real, boolean).  The inputs are optional depending upon what you need the function to do.

 

For example, the following program declares two functions for the perimeter and area of a circle.  Below the function declarations is the main program which calls the functions and uses them to provide output to the user.

 

function circumference(radius : real) : real

    % returns circumference of a circle

    result 2 * 3.14 * radius

end circumference

 

function circleArea(radius : real) : real

    % returns area of a circle = pi * r-squared

    result 3.14 * radius * radius

end circleArea

 

%%%%% main program starts below %%%%%

 

var radius : real

% output C and A for a given radius

put “Enter the radius of your circle: “..

get r

put “C = “, circumference(radius)

put “A = “, circleArea(radius)