19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

on line 5 means “run the subroutine named GlumGluffToInch(), and then<br />

return <strong>to</strong> the line that comes after this subroutine call” (which is line 6 in<br />

this example). It’s like taking a break from cleaning your room <strong>to</strong> go watch<br />

some TV and then coming back <strong>to</strong> pick up where you left off. Figure 10-3<br />

shows how a subroutine works in a program.<br />

Main program<br />

TextWindow.Write(...)<br />

glumGluffs = ...<br />

GlumGluffToInch()<br />

TextWindow.WriteLine(...)<br />

Subroutine<br />

Sub GlumGluffToInch<br />

...<br />

EndSub<br />

Figure 10-3: Showing how GlumGuff2.sb calls the GlumGluffToInch() subroutine<br />

Here is one example of output from this program:<br />

How many glum-gluffs? 8.5<br />

That's about 6.38 inches.<br />

A subroutine can access all the variables in the main program, and<br />

the main program can access all the variables in a subroutine. The variable<br />

glumGluffs was created and assigned a value in the main program<br />

(line 3), but it was used by the subroutine <strong>to</strong> know how many glum-gluffs<br />

it needs <strong>to</strong> convert (line 12). And the variable inches was created inside<br />

the subroutine (line 12), but the main program reads it and displays its<br />

value <strong>to</strong> the user (line 6).<br />

Here are some good reasons <strong>to</strong> put the unit conversion code in<strong>to</strong> a<br />

subroutine:<br />

1. You isolate (or separate) the unit conversion details from the main program.<br />

The main program now doesn’t have <strong>to</strong> worry about how the conversion<br />

is done. This makes your code easier <strong>to</strong> read and maintain.<br />

2. If errors occur, you know where <strong>to</strong> look, which makes debugging much<br />

easier <strong>to</strong> do.<br />

3. You don’t have <strong>to</strong> write the same code over and over again! Without<br />

using subroutines, if a program needs <strong>to</strong> run the same set of statements<br />

more than once, you have <strong>to</strong> duplicate these statements in your code.<br />

But if you put those statements in a subroutine, you can call it from<br />

any point in your program (code reuse). You’ll practice this in the next<br />

section.<br />

NOTE<br />

In this book, we’ll start the name of a subroutine <strong>with</strong> a capital letter. We’ll also write<br />

all the subroutines at the bot<strong>to</strong>m of every main program. We recommend you follow<br />

the same practice in your own programs: it’ll help keep you organized!<br />

132 Chapter 10

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

Saved successfully!

Ooh no, something went wrong!