Visual Basic 2008 memungkinkan prosedur yang akan diulang sebanyak yang selama prosesor dan memori yang dapat mendukung. Hal ini umumnya disebut perulangan. Looping diperlukan bila kita perlu untuk memproses sesuatu yang berulang-ulang sampai kondisi tertentu terpenuhi. Sebagai contoh, kita dapat merancang sebuah program yang menambahkan serangkaian nomor sampai jumlah yang melebihi nilai tertentu, atau program yang meminta pengguna untuk memasukkan data berulang kali hingga kunci dia di kata 'Selesai'. Dalam Visual Basic 2008, kami memiliki tiga jenis Loops, they are the For.....Next loop, the Do loop. and the While.....End while loop
11.1 For....Next LoopThe format is:Sometimes the user might want to get out from the loop before the whole repetitive process is executed, the command to use is Exit For. To exit a For….Next Loop, you can place the Exit For statement within the loop; and it is normally used together with the If…..Then… statement. For its application, you can refer to example 11.1 d. |
| ||||
11.2 Do Loop The formats are a) Do While condition Block of one or more VB statements Loop b) Do Block of one or more VB statements Loop While condition c) Do Until condition Block of one or more VB statements Loop d) Do Block of one or more VB statements Loop Until condition * Exiting the Loop Sometime we need exit to exit a loop prematurely because of a certain condition is fulfilled. The syntax to use is known as Exit Do. Lets examine the following example | Example 11.2(a) Do while counter <=1000 TextBox1.Text=counter counter +=1 Loop * The above example will keep on adding until counter >1000. The above example can be rewritten as Do TextBox1.Text=counter counter+=1 Loop until counter>1000 Example 11.2(b) Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sum, n As Integer Do n += 1 sum += n ListBox1.Items.Add(n & vbTab & sum) If n = 100 Then Exit Do End If Loop Sub In the above example, we find the summation of 1+2+3+4+……+100. In the design stage, you need to insert a ListBox into the form for displaying the output, named List1. The program uses the Add method to populate the ListBox. The statement ListBox1.Items.Add(n & vbTab & sum) will display the values of n and sum and uses the vbTab function to create a space between the headings n and sum. | ||||
11.3 While ...End While Loop The structure of a While….End While is very similar to the Do Loop. it takes the following format:
Statements End While The above loop means that while the condition is not met, the loop will go on. The loop will end when the condition is met. | Example 11.3 Dim sum, n As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sum, n As Integer While n <> 100 n += 1 sum = sum + n ListBox1.Items.Add(n & vbTab & sum) End While End Sub |
Tidak ada komentar:
Posting Komentar