FUNCTION Procedure (QBASIC)


FUNCTION Procedure is just like a SUB Procedure but has a little difference between them. The difference is that FUNCTION Procedure returns a single value to the main part of the program (Main Module). 

It also has three parts, first one is declaration part where we declare FUNCTION procedure, second one is main part, from where FUNCTION procedure is called and last one is FUNCTION part where we define our specific task to do. To understand these 3 parts look at the following example. 

Function Procedure

In the above program we declared the FUNTION procedure by using DECLARE keyword and statements between CLS and END part is main part where code runs and when interpreter read fifth line, flow of program jumps to the FUNCTION procedure. Inside the function procedure it calculate the area and return the value in the main module. After that it print the Area and when it read END statement it terminate the program.  

In this way FUNCTION procedure reads, it returns single value to the main module. We can create more then one functions in the program. Look at the following example.

DECLARE FUNCTION area(l,b)
DECLARE FUNCTION volume(l,b,h)
DECLARE FUNCTION perimeter(l,b)
CLS
INPUT "Enter Length "; l
INPUT "Enter Breadth "; b
INPUT "Enter Height "; h
Ar = area(l, b)
vol = volume(l, b, h)
per = perimeter(l, b)
PRINT "Area = "; Ar
PRINT "Volume = "; vol
PRINT "Perimeter = "; per
END

FUNCTION area (l, b)
    a = l * b
    area = a
END FUNCTION

FUNCTION volume (l, b, h)
    v = l * b * h
    volume = v
END FUNCTION

FUNCTION perimeter (l, b)
    p = 2 * (l + b)
    perimeter = p
END FUNCTION

Example: Program to print whether the given number is odd or even.

DECLARE FUNCTION OddEven$(x)
CLS
INPUT "Enter a Number : "; x
r$ = OddEven$(x)
PRINT x; "is "; r$
END

FUNCTION OddEven$ (x)
    IF x MOD 2 = 0 THEN
        result$ = "Even Number"
    ELSE
        result$ = "Odd Number"
    END IF
    OddEven$ = result$
END FUNCTION

Example: Program to find the greatest number among 3 numbers.

DECLARE FUNCTION greatest(x,y,z)
CLS
INPUT "Enter first number "; a
INPUT "Enter second number "; b
INPUT "Enter third number "; c
gr = greatest(a, b, c)
PRINT "Greatest Number is "; gr
END

FUNCTION greatest (x, y, z)
    IF x > y AND x > z THEN
        g = x
    ELSEIF y > x AND y > z THEN
        g = y
    ELSE
        g = z
    END IF
    greatest = g
END FUNCTION

  8480