15.04.2018 Views

programming-for-dummies

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

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

216<br />

Creating and Using Subprograms<br />

Creating a subprogram<br />

Every subprogram consists of a unique name and one or more commands.<br />

You can name a subprogram anything although it’s usually best to give a<br />

subprogram a descriptive name. So if you create a subprogram to convert<br />

yards into meters, you might name your subprogram Yards2Meters or<br />

MetricConverter.<br />

A descriptive name <strong>for</strong> a subprogram can help you identify the purpose of<br />

that subprogram.<br />

After you define a name <strong>for</strong> your subprogram, you can fill it up with one or<br />

more commands that tell that subprogram what to do. So if you wanted to<br />

write a subprogram that prints your name on-screen, your main subprogram<br />

might look like this:<br />

SUB PrintMyName<br />

FOR I = 1 TO 5<br />

PRINT “John Smith”<br />

NEXT I<br />

END SUB<br />

The preceding BASIC language example defines the beginning of a subprogram<br />

by using the SUB keyword followed by the subprogram’s name,<br />

PrintMyName. The end of the subprogram is defined by the END SUB<br />

keywords.<br />

Not every language defines subprograms with keywords. In the curly bracket<br />

language family, the main program is called main and every subprogram is<br />

just given its own name, such as<br />

print_my_name ()<br />

{<br />

<strong>for</strong> i = 1; i < 5; i++)<br />

{<br />

printf (“John Smith”);<br />

}<br />

}<br />

Instead of using the term subprogram, the curly bracket languages use the<br />

term function.<br />

You can store subprograms in the same file as the main program or in a separate<br />

file. If you store a subprogram in the same file as the main program,<br />

you can place the subprogram at the beginning or end of the file, as shown<br />

in Figure 6-4.

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

Saved successfully!

Ooh no, something went wrong!