Monday, March 7, 2011

Practice #4 - Loops

1. Put a textbox 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 buttons to the form.
   Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
  
     Dim howmany As Integer = TextBox1.Text
  
     Dim x As Integer = 0
  
     ListBox1.Items.Clear()
  
     For x = 1 To howmany
  
       ListBox1.Items.Add(x & " item")
  
     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 os years it would take.
   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
  
       lblThree.Text = ("It will take " & years.ToString("f1") & " years to make the $10,000 goal.")
  
     Next
  
   End Sub
  
 End Class  

3. Write a program that creates a times table.
   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 ofthe other to get this to work.
   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  
     Dim x, y As Integer 
  
     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
  

No comments:

Post a Comment