Wednesday, January 23, 2008

Lesson 3 : Writing the Codes


Now we shall attempt to write the codes for the cylinder program.








Now, doubleclick on the O.K button and enter the codes between Private Sub OK_Click( ) and End Sub

    Private Sub OK_Click( )
    r = Val(radius.Text)
    h = Val(hght.Text)
    pi = 22 / 7
    v = pi * (r ^ 2) * h
    volume.Text= Str$(v)
    End Sub
when you run the program , you should be able to see the interface as shown above. if you enter a value each in the radius box and the height box, then click OK, the value of of the Volume will be displayed in the volume box.

I shall attempt to explain the above source program to newcomers in Visual Basic( If you are a veteran, you can skip this part) . Let me describe the steps using pseudocodes as follows:

Procedure for clicking the OK button to calculate the volume of cylinder
get the value of r from the radius text box
get the value of h from the height text box
assign a constant value 22/7 to pi
calculate the volume using formula
output the results to the Volume text box
End of Procedure





The syntax radius.Text consists of two parts, radius is the name of text box while Text is the textual contents of the text box. Generally, the syntax is: Object.Property
In our example, the objects are radius, hght and volume, each having text as their property.Object and property is separated by a period(or dot).The contents of a text box can only be displayed in textual form, or in programming term,as string. To convert the contents of a text box to a numeric value so that mathematical operations can be performed , you have to use the function Val. Finally, In order to display the results in a text box, we have to perform the reverse procedure, that is, to convert the numeric value back to the textual form, using the function Str$.

I shall also explain the syntax that defines the sub procedure Private Sub OK_click. Private Sub here means that the parameters , values and formulas that are used here belong only to the OK subprocedure(an object by itself).They cannot be used by other sub procedures or modules. OK_Click defines what kind of action the subprocedure OK will response .Here, the action is mouse click. There are other kind of actions like keypress, keyup, keydown and etc that I am going to due with in other lessons.

No comments: