19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

92 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

Object Property Setting<br />

frm4_3_5 Caption Ceil Function<br />

lblNumber Caption Enter a number<br />

txtNumber Text (blank)<br />

cmdCalculate Caption Calculate Ceil<br />

picResults<br />

Private Function Ceil(x As Single) As Single<br />

‘Round nonintegers up<br />

Ceil = -Int(-x)<br />

End Function<br />

Private Sub cmdCalculate_Click()<br />

‘Demonstrate the Ceil function<br />

picResults.Print “Ceil(“; txtNumber.Text; “) =”; Ceil(Val(txtNumber.Text))<br />

txtNumber.Text = “”<br />

txtNumber.SetFocus<br />

End Sub<br />

[Run, type 4.3 into the text box, click the comm<strong>and</strong> button, type 4 into the text box, <strong>and</strong> then click the<br />

comm<strong>and</strong> button again.]<br />

There are many reasons for employing user-defined functions.<br />

1. User-defined functions are consistent with the modular approach to program<br />

design. Once we realize a particular function is needed, we can give it a name<br />

but save the task of figuring out the computational details until later.<br />

2. Sometimes a single formula must be used several times in a program. Specifying<br />

the formula as a function saves repeated typing of the same formula,<br />

improves readability, <strong>and</strong> simplifies debugging.<br />

3. Functions written for one program can be used in other programs. Programmers<br />

maintain a collection, or library, of functions that might be needed.<br />

COMMENTS<br />

1. By default, variables passed to a Function procedure are passed by reference;<br />

that is, their values are subject to being changed by the Function procedure.<br />

Variables also can be passed by value to Function procedures <strong>and</strong> thereby have<br />

their values persist. As with Sub procedures, a variable is passed by value if the<br />

variable is enclosed in an extra pair of parentheses when the function is<br />

invoked, or if the corresponding parameter in the Private Function statement is

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

Saved successfully!

Ooh no, something went wrong!