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

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

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

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

EXAMPLE 2<br />

The following variation of the addition program from the previous section uses a Sub procedure to acquire<br />

the input. The variables x <strong>and</strong> y are not assigned values prior to the execution of the first Call statement.<br />

Therefore, before the Call statement is executed, they have the value 0. After the Call statement is executed,<br />

however, they have the values 2 <strong>and</strong> 3. These values then are passed by the second Call statement<br />

to the Sub procedure Add.<br />

Private Sub cmdCompute_Click()<br />

Dim x As Single, y As Single<br />

‘Display the sum of the two numbers<br />

Call GetNumbers(x, y)<br />

Call Add(x, y)<br />

End Sub<br />

Object Property Setting<br />

frmAdd Caption Add Two Numbers<br />

lblFirstNum Caption First Number<br />

txtFirstNum Text (blank)<br />

lblSecondNum Caption Second Number<br />

txtSecondNum Text (blank)<br />

cmdCompute Caption Compute Sum<br />

picResult<br />

Private Sub Add(num1 As Single, num2 As Single)<br />

Dim sum As Single<br />

‘Display numbers <strong>and</strong> their sum<br />

picResult.Cls<br />

sum = num1 + num2<br />

picResult.Print “The sum of”; num1; “<strong>and</strong>”; num2; “is”; sum<br />

End Sub<br />

Private Sub GetNumbers(num1 As Single, num2 As Single)<br />

‘Record the two numbers in the text boxes<br />

num1 = Val(txtFirstNum.Text)<br />

num2 = Val(txtSecondNum.Text)<br />

End Sub<br />

[Run, type 2 <strong>and</strong> 3 into the text boxes, <strong>and</strong> then click the comm<strong>and</strong> button.]<br />

In most situations, a variable with no preassigned value is used as an argument of a Call<br />

statement for the sole purpose of carrying back a value from the Sub procedure.<br />

EXAMPLE 3<br />

The following variation of Example 2 allows the cmdCompute_Click event procedure to be written in the<br />

input-process-output style.<br />

Private Sub cmdCompute_Click()<br />

Dim x As Single, y As Single, s As Single<br />

‘Display the sum of two numbers<br />

Call GetNumbers(x, y)

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

Saved successfully!

Ooh no, something went wrong!