Sunday, January 4, 2009

Using Subroutines - Lesson 3

The first two lessons show how to write old style BASIC programs which use GOTO. Let's show how to create the hypotenuse calculator in a more structured way using scoped subroutines. Here is the code:

'hypotenuse calculator
global a, b, c, #sideA, #sideB
call displayAll

sub displayAll
print "Hypotenuse Calculator"
print "Length of side A: ";
textbox #sideA, a
print "Length of side B: ";
textbox #sideB, b
button #go, "Go!", computeSideC
if c > 0 then print "Length of side C: "; c
end sub

sub computeSideC key$
a = #sideA value()
b = #sideB value()
c = sqr(a^2+b^2)
call displayAll
end sub

If you compare this example to the one for lesson 2, you'll see most of the code is the same.
  • The first few lines of code kick the program off by calling the displayAll subroutine.
  • The displayAll subroutine adds a button which calls the computeSideC subroutine when it is clicked.
  • The computeSideC subroutine does some math and then calls the displayAll subroutine, forcing the web page to update.

No comments: