Friday, February 25, 2011

Practice 4 Visual Basic Loops

1. Put a textbox, a listbox, and a button on the form. The user must enter a number and press the button. When the button is pressed, it will add that many items to the listbox on the form.


   Private Sub theButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles theButton.Click  
Dim times As Double
times = CDbl(TextBox1.Text)
Dim i, sum As Integer
sum = 0
For i = 1 To times
sum = sum + 1
'show items in listbox
ListBox1.Items.Add(sum & " items")
Next
End Sub
End Class


2. If you were to put away a certain amount of money every month, how many years would it take you to save up $10,000. Use a textbox to gather the amount that is to be put away every month. Use a label to display the number of years it would take.

 Public Class Form1  
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim pay, months, total, goal As Integer
Dim years As Decimal
pay = CInt(txtPay.Text)
goal = 10000
For total = 1 To goal
total += pay
months = months + 1
years = months / 12
Label3.Text = ("It will take " & years.ToString("f1") & " years to make the $10,000 goal.")
Next
End Sub
End Class


3. Write a program that will create a times table.

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
…..
You could use labels or buttons to hold the numbers. Generate these dynamically and add them to the Me.Controls collection.
You will have to use two loops, one inside of the other to get this to work.

 Public Class Form1  
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim x, y As Integer
'Button = 20 pixels
x = 1
Button1.Visible = False
For x = 1 To 10
For y = 1 To 10
Dim newbutton As New Button
newbutton.Location = New Point(50 * x, 50 * y)
newbutton.Width = 40
newbutton.Text = x * y
Me.Controls.Add(newbutton)
Next
Next
End Sub
End Class


A loop within a loop operates in the inside loop until that loop is finished, then goes into the outer loop to get to the next level to run the inner loop again till it is finished.

No comments:

Post a Comment