07.05.2015 Views

Bronze Edition Guide - True BASIC

Bronze Edition Guide - True BASIC

Bronze Edition Guide - True BASIC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

14. Functions and Subroutines 107<br />

In the following short example, answer acquires the value 3.1622777, which is returned by<br />

the function SQR.<br />

LET answer = Sqr(10)<br />

PRINT answer<br />

END<br />

You can think of a function as a machine that takes some numbers or strings as input, and<br />

produces one number or string as output. Functions differ from subroutines in that<br />

• functions can return only one value and<br />

• functions cannot change the values of any parameters sent to them.<br />

Now you’ll see how to define your own functions and use them to break your programs into<br />

logical units.<br />

One-line Functions<br />

One-line functions are the simplest kind of function. You can simulate the rolling of one die<br />

as a one-line function. Here’s the CRAPS program again, rewritten to use a function Rolldie.<br />

! Craps game with one-line function for rolling one die.<br />

!<br />

RANDOMIZE<br />

DEF Rolldie = Int(6*Rnd + 1)<br />

FOR game = 1 to 10<br />

! Roll 1 die<br />

! Play 10 games<br />

LET dice = Rolldie + Rolldie ! Rolldie function twice<br />

SELECT CASE dice<br />

! Branch on roll<br />

CASE 2, 3, 12 ! dice = 2, 3, or 12<br />

PRINT “You lose.”<br />

CASE 7, 11 ! dice = 7 or 11<br />

PRINT “You win.”<br />

CASE ELSE<br />

! Anything else<br />

LET POINT = dice<br />

! Remember that roll<br />

DO<br />

LET dice = Rolldie + Rolldie ! Roll again<br />

LOOP until dice = 7 or dice = point<br />

IF dice=point then PRINT “You win” else PRINT “You lose”<br />

END SELECT<br />

NEXT game<br />

END

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!