Uploaded by tpscheck86

vbprotfolio11-17

advertisement
HOMEWORK HANDOUT
Problem 1: Test Properties
User interface Explanation
This is a very simple program with only 1 button (Figure 1). After the button is clicked a message box
pops up asking the user to enter a short phrase (Figure 2). After clicking OK the text will be transferred
to the form in 2 different settings (Figure 3).
Figure 1
Figure 2
Figure 3
Code Explanation
The code is very simple because all of the settings modification is set with the text box properties. The
code will only ask the user to enter a short phrase via an input box. After the OK button is clicked the
text is copied into both text boxes.
Public Class Form1
Private Sub btnEnter_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnEnter.Click
txtText1.Text = InputBox("Please enter a short phrase")
txtText2.Text = txtText1.Text
End Sub
End Class
Problem 2: Test Properties
User interface Explanation
The starting form contains 3 buttons (Figure 4). The Riddle button calls up the message box shown in
Figure 5. This message box contains a riddle. The Answer button will call up a second message box
which contains the answer to the riddle. The End button terminates the program.
Figure 4
Figure 5
Figure 6
Code Explanation
The first 2 buttons only use the message box command. vbCrLf was used as a return/enter within the
message box. This allowed each statement in the text box to appear on a separate line. The End
command is used for the Exit button.
Public Class Form1
Private Sub btnRiddle_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnRiddle.Click
MessageBox.Show("There is a row of five different color houses." &
vbCrLf & "Each house is occupied by a man of different nationality." &
vbCrLf & "Each man has a different pet, prefers a different drink, and
smokes a different brand of cigarettes." & vbCrLf & "" & vbCrLf & "1. The
Brit lives in the Red house." & vbCrLf & "2. The Swede keeps dogs as pets."
& vbCrLf & "3. The Dane drinks tea." & vbCrLf & "4. The Green house is next
to the White house, on the left." & vbCrLf & "5. The owner of the Green
house drinks coffee." & vbCrLf & "6. The person who smokes Pall Mall rears
birds." & vbCrLf & "7. The owner of the Yellow house smokes Dunhill." &
vbCrLf & "8. The man living in the center house drinks milk." & vbCrLf &
"9. The Norwegian lives in the first house." & vbCrLf & "10. The man who
smokes Blends lives next to the one who keeps cats." & vbCrLf & "11. The
man who keeps horses lives next to the man who smokes Dunhill." & vbCrLf &
"12. The man who smokes Blue Master drinks beer." & vbCrLf & "13. The
German smokes Prince." & vbCrLf & "14. The Norwegian lives next to the Blue
house." & vbCrLf & "15. The man who smokes Blends has a neighbor who drinks
water." & vbCrLf & "" & vbCrLf & "Who has fish at home?")
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnAnswer_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAnswer.Click
MessageBox.Show("The German in the green house owns the Fish.")
End Sub
End Class
LESSON 1
The Basics
Project 1-1: The Information Collection Program
User interface Explanation
When the program is executed, the user is presented with the form shown in Figure 1. This form has no
functionality whatsoever. It is only an example on how to add labels, radio buttons, and text boxes to a
form. There is no code for this program
Figure 1
Project 1-2: The Congratulations Program
User interface Explanation
When the program is executed, the user is presented with the form shown in Figure 2. This form has 2
buttons on it that are anchored to the top left corner of the form. When the Click button is clicked as
message box will pop up with a short phrase (Figure 3). The Exit button will terminate the program.
Figure 2
Figure 3
Code Explanation
The code for this program is very simple. A message box statement is used to create the message box
described earlier. The Exit button contains the End command.
Public Class Form1
Private Sub btnClick_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClick.Click
MessageBox.Show("Congratulations on your success!")
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
LESSON 2
Forms and Decisions
Project 2-1: The Size of a Form Program
User interface Explanation
When the program is executed, the user is presented with the form shown in Figure 1. This form has 2
buttons on it that are anchored to the bottom left corner of the form. If the “Reduce” button is clicked,
the form will reduce itself in size by 100 pixels in both the horizontal and vertical directions. The result
of 1 click is shown in Figure 2. This button can be clicked an unlimited number of times, but after a few
clicks the form becomes too small to display the buttons and all that remains shown is the title bar. The
“Exit” button terminates the programs.
Figure 1
Figure 2
Code Explanation
The code for this program is very easy to understand. The click method for the “Reduce” button is used
to start the resizing process. Once the button is clicked, the program creates 2 new variables; one is set
to the current width of the form, and the other is set to the current height of the form. Once these
values are know, a value of 100 pixels is subtracted from each one. Me.Size is then used to set the form
size to the newly calculated values. The click method for the “Exit” button is attached to the “End”
command.
Public Class Form1
Private Sub btnReduce_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnReduce.Click
Dim intWidth As Integer = Me.Size.Width
Dim intHeight As Integer = Me.Size.Height
intWidth = intWidth - 100
intHeight = intHeight - 100
Me.Size = New Size(intWidth, intHeight)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-2: Double the Form Program
User interface Explanation
When the program is executed, the user is presented with the form shown in Figure 3. This form has 2
buttons on it that are anchored to the bottom right corner of the form. If the “Half” button is clicked,
the form will reduce itself half in both the horizontal and vertical directions. The result of 1 click is
shown in Figure 4. If the “Double” button is clicked, the form will increase itself by 2 in both the
horizontal and vertical directions. The result of 1 click is shown in Figure 5.These buttons can be clicked
an unlimited number of times, but after a few clicks the form becomes too small, or big, to properly
display the form. The “Exit” button terminates the programs.
Figure 3
Figure 4
Figure 5
Code Explanation
The code for this program is very easy to understand. The click method for the “Half” button is used to
start the reduction process. Once the button is clicked, the program creates 2 new variables; one is set
to the current width of the form, and the other is set to the current height of the form. Once these
values are known, they are both divided by 2 using truncated integer division. Me.Size is then used to
set the form size to the newly calculated values. The click method for the “Double” button is used to
start the enlargement process. Once the button is clicked, the program creates 2 new variables; one is
set to the current width of the form, and the other is set to the current height of the form. Once these
values are known, they are both multiplied by. Me.Size is then used to set the form size to the newly
calculated values. The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnEnlarge_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDouble.Click
Dim intHeight As Integer = Me.Size.Width
Dim intwidth As Integer = Me.Size.Height
intwidth = intwidth * 2
intHeight = intHeight * 2
Me.Size = New Size(intwidth, intHeight)
End Sub
Private Sub bthHalf_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles bthHalf.Click
Dim intHeight As Integer = Me.Size.Width
Dim intwidth As Integer = Me.Size.Height
intwidth = intwidth \ 2
intHeight = intHeight \ 2
Me.Size = New Size(intwidth, intHeight)
End Sub
End Class
Project 2-3: Input Box and MessageBox Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 6. This form has 2
buttons on it that contain the necessary code needed to accomplish a task. The “Start” button will bring
up an input box that asks for your hourly wage. This input box is shown in figure 7. After you enter a
value, in this case, 8, you click the OK button. The program then uses this value to estimate your yearly
wage using the standard 40 hour work week as a basis for the calculation. The calculated value is
displayed to you in a message box. This is shown in figure 8. The “Exit” button terminates the
programs.
Figure 6
Figure 7
Figure 8
Code Explanation
The code for this program is very basic. The click method for the “Start” button is used to bring up an
input box that requests your hourly wage. Simultaneously, 2 variables are created and the entered
value is stored in one of them. The other is used for the result of an equation that estimates the yearly
wage. This calculated value is then displayed in a message box that informs the user with their yearly
wage. The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub lblClick_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click
Dim decWage As Decimal
Dim decYearly As Decimal
decWage = CDec(InputBox("Enter your hourly wage."))
decYearly = decWage * 2000
MessageBox.Show("Your Yearly wage is: $" & decYearly.ToString())
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-4: The FileOpenDialog Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 9. This form has 2
buttons on it that contain the necessary code needed to display a filename is a MessageBox. The
“Open” button will bring up Open File Dialog box. This is shown in Figure 10. After you select a file, in
this case, ac lab 2, you click the Open button. This, in turn, displays a MessageBox the displays the full
file path for the selected file. This is shown in Figure 11. The “Exit” button terminates the programs.
Figure 9
Figure 10
Figure 11
Code Explanation
The code for this program is very simple because the properties of the OpenFileDialog are all set from
within the properties window instead of with code. The click method for the “Open” button is used to
show the Open File Dialog window. The user then selects a file from anywhere they wish. After they
click the open button, the full path for the selected file will be displayed in a MessageBox. The click
method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnOpen.Click
OpenFileDialog1.ShowDialog()
MessageBox.Show(OpenFileDialog1.FileName)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-5: The Sandwich Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 12. This form has 2
buttons, 4 radio buttons, and 4 check boxes. The user selects their desired options and when finished,
they click the “Show Sandwich” button. This brings up a series of message boxes that show your
selected options. Figures 13, 14, and 15 show the result when the options shown in Figure 12 are
selected. The “Exit” button terminates the programs.
Figure 13
Figure 12
Figure 14
Figure 15
Code Explanation
The code for this program is very simple because there are only 2 different statements used. After the
user clicks the “Show Sandwich” button, the program will use a series of 9 different IF Statements to
check each of the options. If an option is checked, the program will display a message box for that
option; this will continue until all options have been tested. The click method for the “Exit” button is
attached to the “End” command.
Public Class Form1
Private Sub btnSandwich_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSandwich.Click
If rdbTurkey.Checked Then
MessageBox.Show("Turkey")
End If
If rdbHam.Checked Then
MessageBox.Show("Ham")
End If
If rdbRoastBeef.Checked Then
MessageBox.Show("Roast Beef")
End If
If rdbVeggie.Checked Then
MessageBox.Show("Veggie")
End If
If chkLettuce.Checked Then
MessageBox.Show("Lettuce")
End If
If chkTomato.Checked Then
MessageBox.Show("Tomato")
End If
If chkPickles.Checked Then
MessageBox.Show("Pickles")
End If
If chkMustard.Checked Then
MessageBox.Show("Mustard")
End If
If chkMayonnaise.Checked Then
MessageBox.Show("Mayonnaise")
End If
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-6: The Coin Flip Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 16. This form has 2
buttons on it. The “Calculate” button will bring up an Input Box asking you to enter the number of
heads. This is shown in figure 17. After you click OK a second Input Box will pop up asking you to enter
the number of tails. This is shown in Figure 18. Once you click OK the percentage of heads is
automatically calculated and the result is displayed in a MessageBox. This is shown in Figure 19. The
“Exit” button terminates the programs.
Figure 16
Figure 17
Figure 18
Figure 19
Code Explanation
The code for this program is very simple again. First, the variables are declared. Second, values are
obtained from the user by using Input Boxes. These values are set to 2 of the declared variables. Now
that the program has some values to work with, it can put these into an equation to calculate the
percentage of heads. After the third declared variable obtains its value from the equation, it is displayed
to the user by using the MessageBox command. The click method for the “Exit” button is attached to
the “End” command.
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnCalculate.Click
Dim heads As Integer
Dim tails As Integer
Dim percentage As Double
heads = CInt(InputBox("Enter number of Heads"))
tails = CInt(InputBox("Enter number of Tails"))
percentage = (heads / (heads + tails)) * 100
MessageBox.Show("The Percentage of Heads is: " &
percentage.ToString() & "%")
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-7: The Earned-Run Average Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 20. This form has 2
text boxes and 3 buttons on it. The 2 text boxes are used to obtain 2 different values from the user.
This is shown in figure 21. After the values are entered and the “Calculate” button is clicked, a label will
become visible. This label shows the calculated ERA based on the entered values. This is shown in
Figure 22. The “Clear” button resets the 2 text boxes and label, and the form is restored to the state
shown in Figure 20. The “Exit” button terminates the programs.
Figure 20
Figure 21
Figure 22
Code Explanation
The code for this program is very similar to the previous project. When the “Calculate button is clicked
the program declares 3 variables. Next, values are obtained from the 2 text boxes on the form. These
values are set to 2 of the declared variables. Now that the program has some values to work with, it can
put these into an equation to calculate the earned run average. After the third declared variable obtains
its value from the equation, it is displayed to the user by using a blank label located on the form. The
“Clear” button uses the ResetText command to clear the contents of the 2 text boxes and label. The
click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnCalculate.Click
Dim earnedruns As Double
Dim innings As Double
Dim percentage As Double
earnedruns = CDbl(txtEarnedRunsAllowed.Text)
innings = CDbl(txtInningsPitched.Text)
percentage = ((earnedruns * 9) / innings)
lblAverage.Text = ("The ERA is: " & percentage.ToString)
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtEarnedRunsAllowed.ResetText()
txtInningsPitched.ResetText()
lblAverage.ResetText()
End Sub
End Class
Project 2-8: The Simple Conversion Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 23. This form has 3
buttons on it; one for conversion from centimeters to inches, another for inches to centimeters, and a
third for ending the program. The “Centimeters to Inches” button will bring up Input Box that requests
a value in centimeters. This is shown in figure 24. After you click OK, the converted value is displayed in
a MessageBox as shown in Figure 25. The “Inches to Centimeters” button will bring up Input Box that
requests a value in inches. This is shown in figure 26. After you click OK, the converted value is
displayed in a MessageBox as shown in Figure 27. The “Exit” button terminates the programs.
Figure 23
Figure 24
Figure 26
Figure 25
Figure 27
Code Explanation
The code for this program is just like the previous projects. First, after a button is clicked, variables are
declared. Second, information is obtained from the user. Third, the values are put through an equation.
Fourth, an If statement is used to check to see if the entered value is possible, if it isn’t, the user is
displayed with a message. If it is, the user is displayed with the converted value. The same process is
used for both buttons. The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnCMtoIN_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCMtoIN.Click
Dim cm As Double
Dim inch As Double
cm = CDbl(InputBox("Enter Centimeters"))
inch = (cm / 2.54)
If cm <= 0 Then
MessageBox.Show("There is no Equivalent!")
Else
MessageBox.Show("This is " & inch.ToString() & " inches")
End If
End Sub
Private Sub btnINtoCM_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnINtoCM.Click
Dim inch As Double
Dim cm As Double
inch = CDbl(InputBox("Enter Inches"))
cm = (inch / 0.3937)
If inch <= 0 Then
MessageBox.Show("There is no Equivalent!")
Else
MessageBox.Show("This is " & cm.ToString() & " centimeters")
End If
End Sub
End Class
Project 2-9: The Ordering Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 28. This form has 2
buttons on it that contain the necessary code needed to display 3 entered values from least to greatest.
The “Values” button will bring up 3 Input Boxes. These are shown in Figures 29, 30, and 31. After the
third value is entered, the program will automatically order and display the values from least to
greatest. This is shown in Figure 32. The “Exit” button terminates the programs.
Figure 28
Figure 29
Figure 30
Figure 31
Figure 32
Code Explanation
The code for this program may look a little more complex, but it is still very simple. The “Values” button
is used to declare 6 variables and bring up a series of Input Boxes. Three of the variables are set to the 3
values obtained from the Input Boxes. After the 3 values are obtained, they go through a series of If
Statements that order them from least to greatest. The If Statements also attach the values to the other
3 variables based on their position in the ascending order string. The click method for the “Exit” button
is attached to the “End” command.
Public Class Form1
Private Sub btnValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnValues.Click
Dim
Dim
Dim
Dim
Dim
Dim
one As Integer
two As Integer
three As Integer
first As Integer
second As Integer
third As Integer
one = CInt(InputBox("Enter first value."))
two = CInt(InputBox("Enter second value."))
three = CInt(InputBox("Enter third value."))
If one < two And one < three Then
first = one
ElseIf one > two And one > three Then
third = one
Else
second = one
End If
If two < one And two < three Then
first = two
ElseIf two > one And two > three Then
third = two
Else
second = two
End If
If three < one And three < two Then
first = three
ElseIf three > one And three > two Then
third = three
Else
second = three
End If
MessageBox.Show("In ascending order: " & first.ToString() & ", " & second.ToString() &
", " & third.ToString())
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnExit.Click
End
End Sub
End Class
Project 2-10: The Overtime Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 33. This form has 2
text boxes and 3 buttons on it that contain the necessary code needed to calculate your weekly pay.
Values are entered into the 2 text boxes and the “Calculate” button is then clicked. If the total hours
worked are 40 or less, there will be no overtime pay calculated. This is shown in figure 34. If the total
hours worked is more than 40, overtime pay will be calculated. This is shown in Figure 35. The “Clear”
button restores the form to the state shown in Figure 33. The “Exit” button terminates the programs.
Figure 33
Figure 34
Figure 35
Code Explanation
The code for this program once again follows the same format as the previous projects. First 3 variables
are declared and 2 of them are set to the values obtain from the 2 text boxes. The program then checks
to see if the total hours worked exceeds 40. If it does, an equation that includes overtime pay is used. If
it doesn’t, an equation that doesn’t include overtime pay is used. The result is then displayed to the
user by using a blank label of the form. The “Clear” button uses the ResetText command to reset the 2
text boxes and the label. The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles btnCalculate.Click
Dim HourlyWage As Decimal
Dim Hours As Decimal
Dim WeeklyPay As Decimal
HourlyWage = CDec(txtHourlyWage.Text)
Hours = CDec(txtHours.Text)
If Hours > 40 Then
WeeklyPay = HourlyWage * CDec(40 + 1.5 * (Hours - 40))
Else
WeeklyPay = HourlyWage * 40
End If
lblPay.Text = ("Your weekly pay is $" & WeeklyPay.ToString())
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtHourlyWage.ResetText()
txtHours.ResetText()
lblPay.ResetText()
End Sub
End Class
Project 2-11: The Triangle Inequality Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 36. This form has 3
text boxes and 2 buttons on it that contain the necessary code needed to test the 3 sides of a triangle.
The “Test” button uses the 3 entered values to check if the values could represent a triangle. This is
shown in figures 37, and 39. If the values can’t represent the sides of a triangle, the user receives a
message stating it is not possible. This is shown in Figure 38. If the values can represent the sides of a
triangle, the user receives a message stating that it is possible. This is shown in Figure 40. The “Clear”
button restores the form to the state shown in Figure 36. The “Exit” button terminates the programs.
Figure 37
Figure 36
Figure 39
Figure 38
Figure 40
Code Explanation
The code for this program uses the same concepts as the previous projects. First, 3 variables are
declared and set to the values obtain from the 3 text boxes. The program then checks the 3 inequality
equations to see if a triangle is possible with the current values. If it is, the user will receive an
appropriate message stating that it is possible. If it isn’t, the user will receive an appropriate message
stating that it is not possible. The “Clear” button uses the ResetText command to reset the 3 text boxes.
The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnTest.Click
Dim a As Double
Dim b As Double
Dim c As Double
a = CDbl(txtA.Text)
b = CDbl(txtB.Text)
c = CDbl(txtC.Text)
If a + b > c And a + c > b And b + c > a Then
MessageBox.Show("These values could possibly represent the
three sides of a triangle.")
Else
MessageBox.Show("These values cannot represent the three sides
of a triangle.")
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtA.ResetText()
txtB.ResetText()
txtC.ResetText()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 2-12: The Car Licensing Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 41. This form has 1
button on it that contains the necessary code needed calculate your license fee. The “Calculate Fee”
button will take the value entered in the text box and put is though internal equations to calculate the
necessary fee. The fee will then be displayed in a label. This is shown in figure 42. The “Exit” button
terminates the programs.
Figure 41
Figure 42
Code Explanation
The code for this program is very simple because all that is uses are If statements. First, 2 variables are
declared and one is set to the value of the text box. The value is then put through a series of If
Statements that determine which window your vehicles horsepower fits in. The first If Statement
checks to make sure that the entered value is positive. The second checks to see if it fits in the $25 fee
window. The third checks to see if it fits in the $40 fee window. The fourth checks to see if it fits in the
$65 fee window. And finally, the fifth checks to see if fits in the $120 fee window. The output fee is
based on which window the value fits in. The fee is then displayed in a label on the form. The click
method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnFee_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnFee.Click
Dim fee As Integer
Dim hp As Integer
hp = CInt(txtHP.Text)
If hp <= 0 Then
MessageBox.Show("Value must be a positive non-zero integer")
End If
If hp >= 1 And hp <= 50 Then
fee = 25
End If
If hp > 50 And hp < 100 Then
fee = 40
End If
If hp >= 100 And hp < 150 Then
fee = 65
End If
If hp >= 150 Then
fee = 120
End If
lblFee.Text = ("Your fee is $" & fee.ToString)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Activity 2-1: Auto Loan Payment Calculator
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 43. This form has 3
text boxes and 3 buttons on it that contain the necessary code needed to calculate the monthly
payment on an auto loan. Values are entered into the 3 text boxes and the “Calculate” button is then
clicked. If any of the 3 values are not appropriate, a MessageBox will be displayed stating which one
must be fixed. These are shown in Figures 44, 45, and 46. Once all values are appropriate, a monthly
payment value will be displayed in a label on the form. This is shown in Figure 47. The “Clear” button
restores the form to the state shown in Figure 33. The “Exit” button terminates the programs.
Figure 43
Figure 44
Figure 45
Figure 46
Figure 47
Code Explanation
The code for this program is a little more involved than the previous projects, but is still follows the
same layout. First 4 variables are declared and 3 of them are set to the values obtain from the 3 text
boxes. The program then checks to see if any of them are not appropriate. If the restrictions are
exceeded, the program will prompt the user to enter a new value. If all of the values are suitable, the
program will calculate the monthly payment. The result is then displayed to the user by using a blank
label of the form. The “Clear” button sets the 3 text boxes to 0 and uses the ResetText command to
reset the label. The click method for the “Exit” button is attached to the “End” command.
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCalculate.Click
Dim
Dim
Dim
Dim
Principal As Single
Rate As Single
Term As Single
Payment As Single
Principal = CSng(txtPrice.Text())
Rate = CSng(txtRate.Text())
Term = CSng(txtTerm.Text())
If Rate <= 0 Or Rate > 100 Then
MessageBox.Show("Please enter a valid interest rate between 1% and
100%.")
ElseIf Principal <= 0 Or Principal > 1000000000 Then
MessageBox.Show("Please enter a valid purchase price.")
ElseIf Term <= 0 Or Term > 1000 Then
MessageBox.Show("Please enter a valid loan term.")
Else
Payment = ((Principal * ((Rate / 100) / 12)) / (1 - (1 + (Rate / 100) /
12) ^ -Term))
lblPayment.Text = ("Your Monthly Payment is: $" & Payment.ToString())
End If
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtPrice.Text = 0
txtRate.Text = 0
txtTerm.Text = 0
lblPayment.ResetText()
End Sub
End Class
LESSON 3
Menus, MDIs, and Simple Loops
Project 3-1: The Menu Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 1. This form
contains standard menu items seen in many windows applications. The only button that contains any
functionality is the exit menu item. When clicked, the program is terminated.
Figure 1
Figure 2
Figure 3
Code Explanation
The “Exit” menu option is the only button that has functionality. The “End” command is used to
terminate the program.
Public Class Form1
Private Sub mnuFileExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles mnuFileExit.Click
End
End Sub
End Class
Project 3-2: The MDI Linear Cost Function Program
User Interface Explanation
When the program is executed, the user is presented with the form shown in Figure 4. This form
contains the file menu item, which includes new and exit options. The “New” button creates a new
instance of the Linear Cost Function program that was created in a step by step (Figure 5). Each time
the menu item is clicked, a new form will be created. The “Exit” button terminates the program.
Figure 4
Figure 5
Code Explanation
When the “New” menu item is clicked, a copy of LCFForm is created, set to be the child of the parent
form, and is displayed. When the “Exit” menu item is clicked, the End command terminates the
program. LCFForm is a copy of a program that was constructed in step by step 3.8. This form is used to
solve linear cost function problems. Me.Close is used for the Exit button. This allows each copy to be
closed separately.
Parent Form
Public Class LDFForm
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles mnuFileNew.Click
Dim NewMDIChild As New LCFForm()
NewMDIChild.MdiParent = Me
NewMDIChild.Show()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles mnuFileExit.Click
End
End Sub
End Class
Child Form
Public Class LCFForm
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnCalculate.Click
Dim
Dim
Dim
Dim
CrLf As String = Chr(13) + Chr(10)
StartingValue, UpperLimit, Increment As Integer
ControlVariable As Integer
DirectCost, FixedCost, TotalCost As Decimal
DirectCost = CDec(txtDirectCost.Text)
FixedCost = CDec(txtFixedCost.Text)
StartingValue = CInt(InputBox("Enter the starting value:"))
UpperLimit = CInt(InputBox("Enter the upper limit:"))
Increment = CInt(InputBox("Enter the increment:"))
For ControlVariable = StartingValue To UpperLimit Step Increment
TotalCost = DirectCost * ControlVariable + FixedCost
MessageBox.Show("The cost at " & ControlVariable.ToString & " item is:" & CrLf &
TotalCost.ToString)
Next ControlVariable
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnExit.Click
Me.Close()
End Sub
End Class
Project 3-3: Adding Windows Functions to the MDI Linear Cost Function Program
User Interface Explanation
This is just an extension to the previous program, in which new menu items were added. These items
include, cascade, tile horizontally, and tile vertically (Figure 6). These options are all located under the
“Window” menu item. The cascade button arranges the items as shown in figure 7. The tile horizontally
button arranges the items as shown in figure 8. The tile vertically buttons arranges the items as shown
in figure 9.
Figure 6
Figure 8
Figure 7
Figure 9
Code Explanation
All of the code is identical to the previous projects except for the addition of the 3 buttons and the code
that is required for them. For simplicity, only the new code is shown.
Private Sub CascadeToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
CascadeToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.Cascade)
End Sub
Private Sub TileHorizontallyToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TileHorizontallyToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.TileHorizontal)
End Sub
Private Sub TileVerticallyToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
TileVerticallyToolStripMenuItem.Click
Me.LayoutMdi(MdiLayout.TileVertical)
End Sub
Project 3-4: Plotting a Line Program
User Interface Explanation
This program contains 2 textboxes and 3 buttons (Figure 10). The labels above the textboxes show
which value should be entered into that particular space. The first button takes the values from the
textboxes and generated values for x from -10 to 10. These 3 values are put into the well known
y=mx+b equation and the value of y is calculated. Both x and y will then be displayed in a message box,
for each step of x. The first message box is shown in Figure 11.
Figure 10
Figure 11
Code Explanation
First, variables are declared for x, y, m, and b when the start button is clicked. From there, if statements
are used to make sure there is a value in the textboxes, if there isn’t, a message box is display. If both
values are accepted, the equation to calculate y will be started. The value of x will increment by 2 each
time through the loop, and a message box is displayed showing the current values of x and y. The Clear
button resets the 2 textboxes. The Exit button ends the program with the End command.
Public Class Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click
Dim x, y, m, b As Decimal
Dim a, c As Boolean
If txtm.TextLength < 1 Then
MessageBox.Show("Please enter a value for the slope.")
a = False
Else
m = CDec(txtm.Text)
a = True
End If
If txtb.TextLength < 1 Then
MessageBox.Show("Please enter a value for the y intercept.")
c = False
Else
b = CDec(txtb.Text)
c = True
End If
If a And c = True Then
For x = -10 To 10 Step 2
y = m * x + b
MessageBox.Show("(" & x.ToString & ", " & y.ToString & ")")
Next
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtb.ResetText()
txtm.ResetText()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 3-5: Prime Number Generator Program
User Interface Explanation
This program contains a single button (Figure 12). When the user clicks the Generate button, the
program will display the 41 prime numbers that come after 41. The first displayed number is shown in
Figure 13.
Figure 12
Figure 13
Code Explanation
First, variables are declared for x and y when the start button is clicked. From there, a for loop is used to
generate values of x ranging from 1 to 41. This x value is then put into the quadratic polynomial that
was conceived by Leonhard Euler. The y value is then displayed in a message box that corresponds to
the value of x that was used. This means that the message box will be displayed a total of 41 times.
Public Class Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click
Dim x, y As Integer
For x = 1 To 41
y = x ^ 2 - x + 41
MessageBox.Show(y.ToString)
Next
End Sub
End Class
LESSON 4
Decisions, Looping, Arrays and Searching
Project 4-1: The Printer Selection Program
User Interface Explanation
The Program shown in Figure 1 allows a user to select a printer from the combo box. Once a printer is
selected and the Display Model button is pushed, the selected printer will be added to the list box
(Figure 2). The clear button will reset the combo box back to the blank selection and will clear the
contents of the list box. The Exit button ends the program.
Figure 1
Figure 2
Code Explanation
When the display button is clicked the list box is cleared of any previous entry and then the text selected
in the combo box is directly copied over. The clear button also clears the list box and resets the text in
the combo box and sets focus to it. The exit button uses the End command to terminated the program.
Public Class Form1
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnDisplay.Click
lstQualifying.Items.Clear()
lstQualifying.Items.Add(cboPrinter.Text)
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
lstQualifying.Items.Clear()
cboPrinter.ResetText()
cboPrinter.Focus()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 4-2: The Weigh Too Much Program
User Interface Explanation
This program contains 2 text boxes and 3 buttons (Figure 3). The labels above the text boxes tell the
user what to enter for the calculation to be performed. When the Calculate button is clicked a message
box pops up to tell you how to change caloric intake. If the current weight is more than the desired
weight the message box shown in Figure 4 will be displayed. If the desired weight is more than the
current weight the message box shown in Figure 5 will be displayed. The Clear button will reset both
text boxes and the Exit button will terminate the program.
Figure 3
Figure 4
Figure 5
Code Explanation
First, variables are declared for the 2 text boxes and 3 more for calculations. When the Calculate button
is pressed the values entered into the text boxes are multiplied by 20 and then subtracted from each
other. The difference is then tested to determine if it is negative. If it is, it will be multiplied by negative
1 and displayed in a message box that tells you to decrease your caloric intake by the difference. If it is
positive, the value will be displayed in a message box that tells you to increase your caloric intake. It the
two values are equal to each other, the weight multiplied by 20 will be displayed in a message box. This
value represents the total calorie that should be consumed to maintain their current weight. The Clear
button resets the 2 text boxes and the Exit button terminates the program with the End command.
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCalculate.Click
Dim current, desired, calories1, calories2, result As Single
current = CSng(txtCurrent.Text)
desired = CSng(txtDesired.Text)
calories1 = current * 20
calories2 = desired * 20
result = calories2 - calories1
If result > 0 Then
MessageBox.Show("Increase you calorie intake.
result.ToString & " more calories per day.")
End If
If result < 0 Then
MessageBox.Show("Decrease you calorie intake.
result * -1 & " less calories per day.")
End If
You should consume " &
You should consume " &
If result = 0 Then
MessageBox.Show("You should continue your current consumption rate of "
& calories1.ToString & " calories per day.")
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtCurrent.ResetText()
txtDesired.ResetText()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 4-3: The Unit Conversion Program
User Interface Explanation
This program contains a combo box, textbox, 2 blank label, and 3 buttons (Figure 6). The combo box
contains 14 different conversions to choose from (Figure 7). Once a conversion is selected the proper
label will be added next to the Value textbox. A value is entered into the text box and the Convert
button is clicked. A second label will appear near the bottom with the converted value (Figure 8). The
Clear button resets all inputs and clears the labels. The Exit button terminates the program.
Figure 6
Figure 7
Figure 8
Code Explanation
The first box shows the conversion sub class and the second box shows the unit label, clear, and exit sub
classes. For the conversion sub class 3 variables are declared; one for the combo box index, another for
the value entered by the user, and one for the converted value. Case statements are used for each of
the conversion. Each case statement corresponds to a specific index value of the combo box. The
conversion is calculated within each case statement and the label is written with the converted value.
For the unit label sub class, case statements are once again used. Depending on which index is selected
the proper unit will be written to the label next to the value box. The Clear subclass resets all labels and
inputs. The Exit sub class terminates the program with the End command.
Public Class Form1
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnConvert.Click
Dim Index As Integer = cboConversion.SelectedIndex
Dim value, conversion As Single
value = CSng(txtValue.Text())
Select Case Index
Case 0 'ft to in
conversion = value * 12
lblAnswer.Text = (conversion.ToString & " Inches")
Case 1 'in to ft
conversion = value / 12
lblAnswer.Text = (conversion.ToString & " Feet")
Case 2 'cm to in
conversion = value * 0.393700787
lblAnswer.Text = (conversion.ToString & " Inches")
Case 3 'in to cm
conversion = value * 2.54
lblAnswer.Text = (conversion.ToString & " Centimeters")
Case 4 'mi to m
conversion = value * 1609.344
lblAnswer.Text = (conversion.ToString & " Meters")
Case 5 'm to mi
conversion = value * 0.000621371192
lblAnswer.Text = (conversion.ToString & " Miles")
Case 6 'mi to ft
conversion = value * 5280
lblAnswer.Text = (conversion.ToString & " Feet")
Case 7 'ft to mi
conversion = value * 0.000189393939
lblAnswer.Text = (conversion.ToString & " Miles")
Case 8 '# to oz
conversion = value * 16
lblAnswer.Text = (conversion.ToString & " Ounces")
Case 9 'oz to #
conversion = value * 0.0625
lblAnswer.Text = (conversion.ToString & " Pounds")
Case 10 'km to mi
conversion = value * 0.621
lblAnswer.Text = (conversion.ToString & " Miles")
Case 11 'mi to km
conversion = value * 1.609344
lblAnswer.Text = (conversion.ToString & " Kilometers")
Case 12 'kw to hp
conversion = value * 1.341003
lblAnswer.Text = (conversion.ToString & " Horsepower")
Case 13 'hp to kw
conversion = value * (1 / 1.341003)
lblAnswer.Text = (conversion.ToString & " Kilowatts")
End Select
End Sub
Private Sub cboConversion_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
cboConversion.SelectedIndexChanged
Dim Index As Integer = cboConversion.SelectedIndex
txtValue.ResetText()
lblAnswer.ResetText()
Select Case Index
Case 0
lblUnit.Text
Case 1
lblUnit.Text
Case 2
lblUnit.Text
Case 3
lblUnit.Text
Case 4
lblUnit.Text
Case 5
lblUnit.Text
Case 6
lblUnit.Text
Case 7
lblUnit.Text
Case 8
lblUnit.Text
Case 9
lblUnit.Text
Case 10
lblUnit.Text
Case 11
lblUnit.Text
Case 12
lblUnit.Text
Case 13
lblUnit.Text
End Select
End Sub
= "Feet"
= "Inches"
= "Centimeters"
= "Inches"
= "Miles"
= "Meters"
= "Miles"
= "Feet"
= "Pounds"
= "Ounces"
= "Kilometers"
= "Miles"
= "Kilowatts"
= "Horsepower"
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtValue.ResetText()
lblAnswer.ResetText()
lblUnit.ResetText()
cboConversion.ResetText()
cboConversion.Focus()
End Sub
End Class
Project 4-4: The Cooking a Turkey Program
User Interface Explanation
This program contains 2 buttons (Figure 9). When the user clicks the Start button, the program will
display the cooking time for a turkey weighing from 8 to 30 pounds (Figure 10). The Exit button
terminates the program.
Figure 9
Figure 10
Code Explanation
First, after the start button is clicked, variables are declared for p, t, hours, and minutes. P is initialized
at 7 and the program go to a do loop. It is stay in this loop until p reaches 30. The time is calculated by
using the weight, p, multiplied by 17. The total time is then integer divided by 60 to get a whole number
of hours. Minutes are then found by subtracting the hours multiplied by 60 from the total time. The
cooking time for each turkey weight is then added to the list box. The exit button uses the End
command to terminate the program.
Public Class Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click
Dim p, t, hours, minutes As Integer
p = 7
Do While p < 30
p = p + 1
t = (p * 17)
hours = t \ 60
minutes = t - (hours * 60)
lstTime.Items.Add("An " & p.ToString & " pound turkey should
cook for " & hours.ToString & " hours and " & minutes.ToString & "
minutes.")
Loop
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 4-5: The Untold Wealth Program
User Interface Explanation
This program contains two buttons (Figure 11). It will simulate a person’s wealth if he starts with 50,000
and his total doubles each week. When the user clicks the Start button, the program will display the
week and net worth until it surpasses 100,000,000. When this happens, a message box will display the
total weeks it took to reach that sum (Figure 12).
Figure 11
Figure 12
Code Explanation
First, variables are declared for x and worth when the start button is clicked. From there, a do loop is
used to generate the total net worth. When the net worth exceeds 100 million the loop will exit and a
message box will display. The Exit button uses the End command to terminate the program.
Public Class Form1
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnStart.Click
Dim x, worth As Double
x = 1
worth = 50000
lstList.Items.Add("Week " & x.ToString & ", Your net worth is " &
"$" & worth.ToString & ".")
Do While worth < 100000000
x = x + 1
worth = worth * 2
lstList.Items.Add("Week " & x.ToString & ", Your net worth is
$" & worth.ToString & ".")
If worth > 100000000 Then
MessageBox.Show("Your net worth has exceded $100,000,000 in
only " & x.ToString & " weeks.")
End If
Loop
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 4-6: The Rnd Function Program
User Interface Explanation
This program contains 4 buttons and a list box (Figure 13). When the user clicks the Generate button,
the program will display 20 random numbers and the line that it is on (Figure 14). When the Search
button is click an input box will pop up asking you to enter a value between 0 and 99 (Figure 15). After
clicking the OK button, 2 possible message boxes will be displayed. The first is displayed if the value is
found in the list. The message box states that the value was found and also what line it is on (Figure 16).
The second is displayed if the value is not found in the list. This one states that the value was not found
(Figure 17). The Clear button will reset the list box. The Exit button will terminate the program.
Figure 13
Figure 14
Figure 15
Figure 16
Figure 17
Code Explanation
First, an array with a capacity of 20 is declared when the program is started. Then variables are declared
for x and z when the generate button is clicked. From there, a for loop is used to generate 20 random
values of x ranging from 0 to 99. Z is used to keep track of which line the value will be placed on. Each
value is added to the list box each time through the loop. The Search button uses the linear search
method to find a target value entered by the used. It uses a for loop to compare the target with each
value in the array. If the value is found an appropriate message will be displayed stating which line the
value can be found on. If it is not found, a message will pop up stating so. The Clear button clears the
list box, and also uses array.clear to erase the values in the array.
Public Class Form1
Dim numbers(20) As Integer
Private Sub btnGenerate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnGenerate.Click
Dim x, z As Integer
z = 0
For index = 0 To 19
Randomize()
x = CInt(100 * Rnd())
numbers(index) = x
z = z + 1
lstNumbers.Items.Add(z.ToString & ". " & numbers(index))
Next
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSearch.Click
Dim target, index As Integer
target = CInt(InputBox("Please enter a target value between 0 and 99"))
For index = 0 To 19
If target = numbers(index) Then
MessageBox.Show("The number " & target.ToString & " was found in line " &
(index + 1).ToString & ".")
Exit For
End If
Next
If index > 19 Then
MessageBox.Show("The number " & target.ToString & " was not found.")
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnClear.Click
lstNumbers.Items.Clear()
Array.Clear(numbers, 0, 19)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnExit.Click
End
End Sub
End Class
Project 4-7: Creating a Lookup Table Program
User Interface Explanation
This program contains 4 buttons and a list box (Figure 18). It is unknown to the user, but when the
program starts, a table of factorials is generated from 0 to 15 in the background. The Lookup Factorial
button is used to allow the user to enter a value from 0 to 15 (Figure 19). This value is then looked up in
the table of factorials and the output is displayed in a label on the lower left side of the form (Figure 20).
The Display Table button will display the complete table of factorials that was generated at the start
(Figure 21). The Clear button returns the program to the state shown if Figure 18. The Exit button will
terminate the program.
Figure 18
5
Figure 19
Figure 20
Figure 21
Code Explanation
First, an array with a capacity of 16 is created. Next, while the form is loading, the factorials for values
from 0 to 15 are being calculated. These values are stored in the array. When the Lookup button is
pressed, a message box pops up and asks the user to enter a value from 0 to 15. If the enter value does
not fall in this range, it will be rejected and the message box will continue to ask for a value. When the
value is accepted, it is used to go to that position in the array. The value is then displayed in a label. The
Display Table button is used to show the complete table of factorials in the list box. The Clear button
resets the form to the starting state. The Exit button uses End command to terminate the program.
Public Class Form1
Dim factorial(16) As Long
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Dim y As Long
Dim x As Integer
y = 1
factorial(0) = 1
For x = 0 To 14
y = y * (x + 1)
factorial(x + 1) = y
Next
End Sub
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnDisplay.Click
Dim x As Integer
For x = 0 To 15
lstDisplay.Items.Add(x & "!= " & factorial(x))
Next
End Sub
Private Sub btnLookup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnLookup.Click
Dim value As Integer
Do
value = Val(InputBox("Please enter a value between 0 and 15:"))
Loop Until 0 <= value And value <= 15
lblFactorial.Text = (value & "!= " & factorial(value))
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnClear.Click
lblFactorial.ResetText()
lstDisplay.Items.Clear()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnExit.Click
End
End Sub
End Class
Project 4-8: The Median Program
User Interface Explanation
This program contains a text box, list box, and 4 buttons (Figure 22). The user is instructed to enter a
value in the text box and when the Add to List button is clicked, the value in the text box is transferred
to the list box; an unlimited number of values can be added to the list box (Figure 23). The user should
then click the Find Median button. This button sorts the values in the list box and calculates the median
and average (Figure 24). The Clear button returns the form back to the state shown in Figure 22. The
Exit button terminates the program.
Figure 22
Figure 23
Figure 24
Code Explanation
When the Add to List button is clicked the value in the text box is checked with an IF statement to
determine whether a value was entered into the text box. If the value is acceptable, the item is added
to the list and the focus is set back to the text box. When the Find Median button is clicked a bunch of
variables are declared which are necessary for the calculations. The step is to take the values from the
list box and add them to an array. The next step is to sort the array in ascending order and then rewrite
the formatted values to the list box. The next step is to determine if the number of values is even or
odd. If the number of values is odd, the calculation finds the value that is located in the center position.
If the number of values is even, the calculation determines the value above and below the center
position. These to values are then added and divided by 2 to determine the median. The Clear button
resets the form to the staring state. The Exit button uses the End command to terminate the program.
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnAdd.Click
Dim value As Double
If txtValue.TextLength < 1 Then
MessageBox.Show("A value must be entered into the text box")
Else
value = CDbl(txtValue.Text)
lstValues.Items.Add(value.ToString)
txtValue.ResetText()
txtValue.Focus()
End If
End Sub
Private Sub btnMedian_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnMedian.Click
Dim high, low, index, z, max As Integer
Dim upper, lower, values(lstValues.Items.Count - 1) As Single
Dim md, average As Double
z = -1
max = lstValues.Items.Count - 1
For index = 0 To max Step 1
z = z + 1
values(index) = lstValues.Items(z)
Next
Array.Sort(values)
lstValues.Items.Clear()
For index = 0 To max Step 1
lstValues.Items.Add(values(index))
Next
low = 0
high = lstValues.Items.Count - 1
average = values.Average
If high Mod 2 = 0 Then
md = (low + high) / 2
MessageBox.Show("The median of this data is " & lstValues.Items(md).ToString & ", and the
average is " & Math.Round(average, 3))
Else
high = high + 1
md = (low + high) / 2
upper = lstValues.Items(md)
lower = lstValues.Items(md - 1)
md = (upper + lower) / 2
MessageBox.Show("The median of this data is " & md.ToString & ", and the average is " &
Math.Round(average, 3))
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnClear.Click
lstValues.Items.Clear()
txtValue.ResetText()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnExit.Click
End
End Sub
End Class
Project 4-9: The Prime Number Program
User Interface Explanation
This program contains a text box, list box, and 3 buttons (Figure 25). The user should first enter any
integer into the test box. After the integer is typed, the Test button should then be pushed. Pushing
this button cause the list box to be filled with that integer’s divisors (Figure 26). If a prime number is
entered there will only be 1 divisor and a message box will display stating that the entered integer is a
prime number (Figure 27). The clear button returns the form to the state shown in Figure 25. The Exit
button terminates the program.
Figure 25
Figure 26
Figure 27
Code Explanation
First, when the Test button is clicked, variables are declared for x and value. The text box is then
checked using an IF Statement to make sure a value is entered. If it is accepted, the number in the text
box is set to the value variable. A For Loop the uses the Mod function to check the value with the
generated value of x. X can be any number from 1 to half of the entered value. The Mod statement
uses an IF statement to see if the value is evenly divisible by any of the generated values of x. If the IF
statement is true, that value of x will be added to the list box. The final test occurs after all values of x
were tested. An IF statement counts the number of items in the list box; if it is 1, a message box will
display stating that the integer was a prime number. The Clear button resets the inputs and outputs to
the starting state. The End command is used with the Exit button to terminate the program.
Public Class Form1
Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnTest.Click
Dim value, x As Integer
If txtValue.TextLength < 1 Then
MessageBox.Show("A value must be entered first!")
Else
value = CInt(txtValue.Text)
End If
For x = 1 To value \ 2
If value Mod x = 0 Then
lstDivisors.Items.Add(x)
End If
Next
If lstDivisors.Items.Count = 1 Then
MessageBox.Show(value.ToString & " is a prime number.")
End If
End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClear.Click
txtValue.ResetText()
lstDivisors.Items.Clear()
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnExit.Click
End
End Sub
End Class
Project 4-10: The Euclidean Algorithm Program
User Interface Explanation
This program contains a single button (Figure 28). When the user clicks the Enter Values button, the
program will display 2 consecutive message boxes(Figures 29 & 30). Once it receives the second
number, a message box will display and state the greatest common factor of the 2 entered numbers
(Figure 31).
Figure 28
Figure 29
Figure 30
Figure 31
Code Explanation
First, after the Values button is clicked, variables are declared for x, y, q, r and gcf. From there, x and y
are set to the values entered into the 2 input boxes. Q is then found using integer division, and r is
found using the Mod operator. If r equals 0, then values are divisible by each other and the gcf is found.
If they are not, a loop will be started and will run until r is 0. Within the loop, x will become y and y will
become r. A new value is found using the mod operator again. If it equals 0 the loop will exit; if it does
not equal 0, the values will switch and the loop will be continue until r equals 0. As soon as r equals 0, a
message box will display to state what the greatest common factor is.
Public Class Form1
Private Sub btnValues_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnValues.Click
Dim x, y, q, r, gcf As Integer
x = CSng(InputBox("Enter your first positive number."))
y = CSng(InputBox("Enter your second positive number."))
q = x \ y
r = x Mod y
If r = 0 Then
gcf = y
Else
Do Until r = 0
x = y
y = r
r = x Mod y
Loop
gcf = y
End If
MessageBox.Show("The greatest commom factor is " & gcf.ToString)
End Sub
End Class
Download