Handout-4 Structured Programming - Repetition The syntax for repetition structure is: For counter=startvalue to endvalue [Step stepvalue] instructions Next counter An example code is the following: Dim x as integer For x = 0 to 10 step 1 Some instructions next x Create an application and add a button and a combo box (default name is ComboBox1). Add the following code: Me.ComboBox1.Items.Clear() Dim x As Integer For x = 1995 To 2004 Step 1 Me.ComboBox1.Items.Add(x) Next The statement Me.ComboBox1.Items.Clear() will clear all the contents of the combo box. To add items to the list, we use the items.add method. Change the step to 2 and then 3 and evaluate its impact. Now load a picture box with the name (plan.ico) into the form. Place the picture on the left edge of the form and note down the value in the Location (X and Y) property (X refers to the distance from the left edge and Y being the distance from the top edge of the form). Do the same by moving the image to the right edge of the form. Write the code to move the image left to right. Dim i As Single For i = 0 To 500 Step 0.1 Me.PictureBox1.Left = i Next How do you speed up and down the movement? Now add another picture called PictureBox2 (cloud.ico). When the car reaches the right edge of the form we want to replace the picture (car) with the picture of the cloud. In the form_load event make PictureBox2 invisible. To replace the picture in PictureBox1 the syntax is Me.PictureBox1.Image = Me.PictureBox2.Image. Similarly write the code to make it move top to bottom and the code to stretch the image. Update Shopping cart example: Dim i As Integer 1 For i = clbCart.Items.Count - 1 To 0 Step -1 If clbCart.GetItemChecked(i) = True Then clbCart.Items.RemoveAt(i) Else strOrder = strOrder & vbNewLine & clbCart.Items(i) End If Next Practice Problems: Calculate answers for 1. 10*10 + 11*11 + 12*12+......+ 22*22. 2. (5-1) + (6-2) + (7-3) + (8-4) + (9-5) + (10-5) Other Repetition Structures VB.NET supports two other forms of repetition and these are: Do While condition instructions loop Do Until condition instructions Loop The first one loops as long as a condition is true. The second one loops until a condition becomes true. Add a combo box and a button and write the following code behind the button. Dim i As Integer Me.ComboBox1.Items.Clear() i = 1 Do While i <= 10 Me.ComboBox1.Items.Add(i) i = i + 1 Loop For i= 1 to 10 step 1 Me.ComboBox1.Items.Add(i) next How many times did the loop execute? It is important to remember that instructions within the loop should change the condition. Otherwise either the instructions will never be executed or they will be an infinite loop. Experiment by changing the increment value to i = 2*i. Use the above repetition structures to figure out the following: Write a program that will calculate the number of years in which an initial deposit amount will reach $1million, with a 7% interest rate. Design an interface with a textbox (name:txtamnt), a button and a label (name:lblyears). With a click of the button the program should calculate the number of years in which the amount will accumulate to $1m. Define two counter variables 2 called sum and nyears. Set the nyears initially to 0 and the sum to the value in the textbox. Now write a loop that will repeat until the sum becomes 1000000 and keep track of the number of years. Complete the program, test and run it. Now what happens when you put 0 in the initial amount? This is an infinite loop. Avoid this by checking if the value is a positive number and if it is then exit the program. Practice Program Suppose $15,000 dollars is deposited in a bank. The bank provides a return of 5% at the end of the year. Also, at the end of each year $1000 is withdrawn. In how many years does the money in the bank get completely depleted? Dim amount, year as integer Amount=15000 year=0 Do while amount >=0 Amount=amount*1.05 year=year+1 Amount=amount-1000 Loop LblDisplay.text=year Random Number Generation We use RANDOMIZE() and RND() function. RND() generates a random number that lies within the following range: 0 <= RND() < 1. To produce random integers in a given range, use this formula: Int((upperbound - lowerbound + 1) * Rnd() + lowerbound) In our example we want to move the two rockets by a random integer number between 1 and 10. The code is: Dim num1, num2 As Integer num1 = Int(10 * Rnd() + 1) num2 = Int(10 * Rnd() + 1) End If Now we will write a program to race two rocket ships. Place two picture box controls near the bottom of the form and add the picture of the rocket ship to the two images. Name the two images picrock1 and picrock2. Place the two rockets side-by-side. Note that at the top of the form the top property is 0. Add three buttons for start, reset, and exit. Note the Y value of the Location property. Suppose it is 280. In the Reset button write the following code. Me.picrock1.Top = 280 Me.picrock2.Top = 280 The above code puts the two pictures at the bottom of the form. Now add a timer control to the form. Set the interval property to 200. Add the following code: Start Button: 3 Me.Timer1.Enabled = True Reset Button: Me.Timer1.Enabled = False Now write the following code in the timer’s Tick event. Me.picrock1.Top = Me.picrock1.Top - 50 Me.picrock2.Top = Me.picrock2.Top - 50 If Me.picrock1.Top <= 0 Or Me.picrock2.Top <= 0 Then Me.Timer1.Enabled = False End If The logic for the above is that the two pictures keep moving up until one of them reaches the top. Then the timer is turned off. To make the program interesting we need to add an element of randomness to it. Complete this code by checking for the winner. You simply need to compare the top properties of the two pictures. Code the reset button and ensure that start and reset are enabled correctly. Now provide an option for the user to bet on one of the rockets to win. You can do this through radio buttons. Hint: a person wins the bet if the rocket they choose wins – if there is a draw or the rocket loses then they lose. Practice Programs 1. Simulate rolling of a dice. Use a label to display the number (1 to 6) that comes up. 2. Create a program for users to take a math quiz. Two random numbers (integers between 1 and 200) should be generated. Then the user would enter the sum of the two numbers generated. If the answer they provide is correct, increment the number of correct answers by 1. Otherwise, increment the number of incorrect answers by 1. Note that the user should be able to repeatedly take the quiz. 3. Create an automatic bouncing ball program (a ball automatically bounces horizontally, vertically or any directions). Scroll Bars We will now explore another object from the toolbox - scroll bar (actually there are two of these, a horizontal and a vertical bar). The scroll bar has an integer value attached to it. The other properties of interest are: minimum, maximum, smallchange, largechange. The value assigned to a scroll bar can be accessed through the property Value. The event that is commonly used here is the Scroll (which is activated when the position of the scroll bar changes). Create a scroll bar with min, max, smallchange and largechange set at 0,100,1,5. Create a label and have the value of the scroll bar displayed in the label. Now attempt the following: Recall that all color schemes are based on three base colors: Red, Green and Blue. By varying the intensity of these three colors, one can produce all other colors. In VB, each of these colors can take an integer value between 0 and 255 4 Create a program to visually see this effect - by changing the background color of a label and setting the intensity of three colors through scroll bars. Note that in the above the same code needs to be written for all the three scroll bars. Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles HScrollBar1.Scroll, HScrollBar2.Scroll, HScrollBar3.Scroll Me.Label1.BackColor = Color.FromArgb(Me.HScrollBar1.Value, Me.HScrollBar2.Value, Me.HScrollBar3.Value) End Sub Practice Problems: 1. Create a program to add 4 integer numbers (range of each is from 1 to 500). For each number to be entered use a scrollbar and a corresponding textbox. 2. Create a program to test a user’s color blindness. Pick about half a dozen colors and see if the user can correctly guess those colors. 5