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.

The second task performed by the addition program also can be h<strong>and</strong>led by a Sub procedure.<br />

The values of the two numbers, however, must be transmitted to the Sub procedure.<br />

This transmission is called passing.<br />

EXAMPLE 2<br />

The following revision of the program in Example 1 uses a Sub procedure to accomplish the second task.<br />

The statement Call Add(2, 3) causes execution to jump to the Private Sub Add(num1 As Single, num2 As<br />

Single) statement, which assigns the number 2 to num1 <strong>and</strong> the number 3 to num2.<br />

Call Add(2, 3)<br />

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

After the lines between Private Sub Add (num1 As Single, num2 As Single) <strong>and</strong> End Sub are executed,<br />

execution continues with the line following Call Add(2, 3), namely, the End Sub statement in the event<br />

procedure. Note 1: When you create the Sub procedure Add, you must type in “(num1 As Single, num2<br />

As Single)” after leaving the Add Procedure dialog box.<br />

Private Sub cmdAdd_Click()<br />

‘Display the sum of two numbers<br />

picResult.Cls<br />

Call ExplainPurpose<br />

picResult.Print<br />

Call Add(2, 3)<br />

End Sub<br />

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

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

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

End Sub<br />

Private Sub ExplainPurpose()<br />

‘Explain the task performed by the program<br />

picResult.Print “This program displays a sentence”<br />

picResult.Print “identifying two numbers <strong>and</strong> their sum.”<br />

End Sub<br />

Sub procedures make a program easy to read, modify, <strong>and</strong> debug. The event procedure<br />

gives a description of what the program does <strong>and</strong> the Sub procedures fill in the details.<br />

Another benefit of Sub procedures is that they can be called several times during the execution<br />

of the program. This feature is especially useful when there are many statements in the<br />

Sub procedure.<br />

EXAMPLE 3<br />

The following extension of the program in Example 2 displays several sums.<br />

Private Sub cmdAdd_Click()<br />

‘Display the sums of several pairs of numbers<br />

picResult.Cls<br />

Call ExplainPurpose<br />

picResult.Print<br />

Call Add(2, 3)<br />

Call Add(4, 6)<br />

Call Add(7, 8)<br />

End Sub<br />

Sub Procedures, Part I 75

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

Saved successfully!

Ooh no, something went wrong!