94 18 Functions Functions are in many ways similar to procedures but there is one major difference – they always calculate a result which may be a number or a string. BASIC already contains a number of functions. For example the function SQR returns the square root of a number. The square root of 16 is 4 so the statements Y = SQR(16) and make sense. The first example calculates the square root of 16 and places the result in Y. Compare this to a procedure – for example the one above, to draw a box. The procedure makes things happen (a box appears on the screen) but it does not produce a numeric or a string value. Functions always produce a numeric or string result.
PRINT SQR(16) If you have a reasonable understanding of procedures and parameters then you can probably cope with this example of a function: 10 PRINT "GIVE ME THREE NUMBERS "; 20 INPUT A,B,C 30 PRINT "THE SUM OF THE NUMBERS IS "; 40 PRINT FNSUM(A,B,C) 50 END 100 DEF FNSUM(X,Y,Z) 105 LOCAL K 110 K=X+Y+Z 120 =K >RUN GIVE ME THREE NUMBERS ?2,4,4 THE SUM OF THE NUMBERS IS 10 Again this program is not of much use – we are using a sledge hammer to crack a nut – but we had better learn to walk before we run! The function is defined in lines 100 to 120 and three parameters are passed to the function.
A, B and C are the actual parameters and the numbers in A, B and C are passed to formal parameters X, Y and Z. For the sake of illustration a local variable K has been used. Line 110 sets K equal to the sum of X, Y and Z. Line 120 shows the way in which a function is ended. It says that the function FNSUM has the value of K.